首先,我们编写一个MyImageButton类,继承自LinearLayout
class="code_img_closed" src="/Upload/Images/2014071509/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('0cbaf35e-a9e3-40e9-bb9d-701db4dd9708',event)" src="/Upload/Images/2014071509/2B1B950FA3DF188F.gif" alt="" />public class MyPhoneImageButton:LinearLayout { private ImageView mButtonImage = null; private TextView mButtonText = null; public MyPhoneImageButton (Context context) : base (context) { mButtonImage = new ImageView(context); mButtonText = new TextView(context); mButtonImage.SetPadding(0, 0, 0, 0); mButtonText.SetPadding(0, 0, 0, 0); //设置本布局的属性 Clickable = true; Focusable = true; AddView (mButtonText); AddView (mButtonImage); } public void setImageResource(int resId) { mButtonImage.SetImageResource(resId); } public void setText(string resId) { mButtonText.Text=resId; } public void setTextColor(int color) { mButtonText.SetTextColor(Resources.GetColor (color)); } }View Code
然后在main布局中为我们自定义的Button写xml布局,注意,我们的“按钮”实际上是一个线性布局,因此xml中应该写LinearLayout而不是Button或者ImageButton
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvPPhone" android:orientation="horizontal" />View Code
最后,在Activity中为我们自定义的按钮设置监听
private LinearLayout llbtDataConfig = null; //main布局中包裹本按钮的容器 private MyPhoneImageButton btDataConfig = null; btDataConfig = new MyPhoneImageButton (this); btDataConfig.setTextColor (Resource.Color.text_color_projectInfo); btDataConfig.setText ("我是文字"); btDataConfig.setImageResource (Resource.Drawable.phone); llbtDataConfig=FindViewById<LinearLayout> (Resource.Id.tvPPhone); llbtDataConfig.AddView(btDataConfig); llbtDataConfig.SetOnClickListener (new llbtDataConfig_Click()); //监听事件继承 public class llbtDataConfig_Click : Java.Lang.Object, View.IOnClickListener { public void OnClick(View v) { } }View Code
另外发现监听不如点击事件好用。
llbtDataConfig.Click += (object sender, EventArgs e) => { llbtDataConfig_Click (); };