首页 > 代码库 > Mono自定义图片按钮

Mono自定义图片按钮

首先,我们编写一个MyImageButton类,继承自LinearLayout

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布局中为我们自定义的Buttonxml布局,注意,我们的“按钮”实际上是一个线性布局,因此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 ();            };