实际上,ImageButton是不能添加文字的,所以我选择将ImageView控件和TextView控件封装在一个LinearLayout里面,整个LinearLayout就是一个按钮,然后对它监听单击等动作。
首先贴上layout.xml里面的布局设计:
01 | < LinearLayout |
02 |
android:layout_width = "wrap_content" |
03 |
android:layout_height = "wrap_content" |
04 |
android:orientation = "vertical" |
05 |
android:id = "@+id/bt" > |
06 |
< ImageView |
07 |
android:id = "@+id/ib" |
08 |
android:layout_width = "wrap_content" |
09 |
android:layout_height = "wrap_content" |
10 |
android:src = "@drawable/ringlove" |
11 |
android:background = "#00000000" |
12 |
/> |
13 |
< TextView |
14 |
android:id = "@+id/tv" |
15 |
android:layout_width = "wrap_content" |
16 |
android:layout_height = "wrap_content" |
17 |
android:text = "@string/cs" |
18 |
android:paddingLeft = "20px" |
19 |
/> |
20 | </ LinearLayout > |
然后是java代码实现:(注意,
m_ll.setClickable(true);这句一定不能少)
01 | package com.droidX.wcs233; |
02 |
|
03 | import android.app.Activity; |
04 | import android.graphics.Color; |
05 | import android.os.Bundle; |
06 | import android.view.MotionEvent; |
07 | import android.view.View; |
08 | import android.view.View.OnClickListener; |
09 | import android.view.View.OnTouchListener; |
10 | import android.widget.LinearLayout; |
11 | import android.widget.Toast; |
12 |
|
13 | public class testActivity extends Activity { |
14 |
LinearLayout m_ll; |
15 |
/** Called when the activity is first created. */ |
16 |
@Override |
17 |
public void onCreate(Bundle savedInstanceState) { |
18 |
super .onCreate(savedInstanceState); |
19 |
setContentView(R.layout.main); |
20 |
m_ll=(LinearLayout)findViewById(R.id.bt); |
21 |
m_ll.setClickable( true ); |
22 |
m_ll.setOnClickListener(ocl); |
23 |
m_ll.setOnTouchListener(otl); |
24 |
} |
25 |
|
26 |
public OnClickListener ocl= new OnClickListener() { |
27 |
|
28 |
@Override |
29 |
public void onClick(View v) { |
30 |
// TODO Auto-generated method stub |
31 |
Toast.makeText(getApplicationContext(), "yes" , Toast.LENGTH_SHORT).show(); |
32 |
} |
33 |
}; |
34 |
|
35 |
public OnTouchListener otl= new OnTouchListener() { |
36 |
|
37 |
@Override |
38 |
public boolean onTouch(View v, MotionEvent event) { |
39 |
// TODO Auto-generated method stub |
40 |
if (event.getAction()==MotionEvent.ACTION_DOWN) |
41 |
{ |
42 |
m_ll.setBackgroundColor(Color.rgb( 127 , 127 , 127 )); |
43 |
} |
44 |
else if (event.getAction()==MotionEvent.ACTION_UP) |
45 |
{ |
46 |
m_ll.setBackgroundColor(Color.TRANSPARENT); |
47 |
} |
48 |
return false ; |
49 |
} |
50 |
}; |
51 | } |
这样就可以了。
另外,为了使“按钮”美观,大家在选择图片的时候,尽量选择长宽不一样的,适合需要的比例,这样配着文字,刚好可以使“按钮”呈正方形。
转自:http://www.th7.cn/Article/bc/Android/201104/20110411192530.html
转自:http://www.th7.cn/Article/bc/Android/201104/20110411192530.html