实际上,ImageButton是不能添加文字的,所以我选择将ImageView控件和TextView控件封装在一个LinearLayout里面,整个LinearLayout就是一个按钮,然后对它监听单击等动作。
|
首先贴上layout.xml里面的布局设计:
02 | android:layout_width = "wrap_content" |
03 | android:layout_height = "wrap_content" |
04 | android:orientation = "vertical" |
08 | android:layout_width = "wrap_content" |
09 | android:layout_height = "wrap_content" |
10 | android:src = "@drawable/ringlove" |
11 | android:background = "#00000000" |
15 | android:layout_width = "wrap_content" |
16 | android:layout_height = "wrap_content" |
17 | android:text = "@string/cs" |
18 | android:paddingLeft = "20px" |
然后是java代码实现:(注意,
m_ll.setClickable(true);这句一定不能少)
01 | package com.droidX.wcs233; |
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; |
13 | public class testActivity extends Activity { |
15 | /** Called when the activity is first created. */ |
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); |
26 | public OnClickListener ocl= new OnClickListener() { |
29 | public void onClick(View v) { |
31 | Toast.makeText(getApplicationContext(), "yes" , Toast.LENGTH_SHORT).show(); |
35 | public OnTouchListener otl= new OnTouchListener() { |
38 | public boolean onTouch(View v, MotionEvent event) { |
40 | if (event.getAction()==MotionEvent.ACTION_DOWN) |
42 | m_ll.setBackgroundColor(Color.rgb( 127 , 127 , 127 )); |
44 | else if (event.getAction()==MotionEvent.ACTION_UP) |
46 | m_ll.setBackgroundColor(Color.TRANSPARENT); |
这样就可以了。
另外,为了使“按钮”美观,大家在选择图片的时候,尽量选择长宽不一样的,适合需要的比例,这样配着文字,刚好可以使“按钮”呈正方形。