Android自定义按钮

来源:互联网 发布:极客学院 php 百度云 编辑:程序博客网 时间:2024/06/14 03:40

系统的Button不支持文字和图片同时上下显示,可以做,但是无法支持控制图片大小,自定义代码如下:

1、建立按钮的内部布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageView1"        android:layout_width="35dp" //设置图片大小        android:layout_height="35dp"         android:layout_gravity="center"/>    <TextView        android:id="@+id/textView1"        android:layout_width="70dp"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:gravity="center"        android:textColor="#ffffff"        android:layout_marginBottom="2dp" /></LinearLayout>

2、代码实现:

public class ImageBtn extends LinearLayout{private ImageView imageView;    private TextView  textView;         public ImageBtn(Context context) {        super(context);        // TODO Auto-generated constructor stub    }    public ImageBtn(Context context, AttributeSet attrs) {        super(context, attrs);        // TODO Auto-generated constructor stub        LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        inflater.inflate(R.layout.imagebutton, this);        imageView=(ImageView) findViewById(R.id.imageView1);        textView=(TextView)findViewById(R.id.textView1);    }         /**     * 设置图片资源     */     public void setImageResource(int resId) {         imageView.setImageResource(resId);     }         /**     * 设置显示的文字     */     public void setTextViewText(String text) {         textView.setText(text);     }        public void setTextViewText(int resId){    textView.setText(resId);    }}


3、在主页面布局中调用:

            <com.microntek.bluetooth.ui.ImageBtn                android:id="@+id/pub_dial"                android:layout_width="fill_parent"                android:layout_height="0dp"                android:layout_weight="1"                android:background="@drawable/left_btn_bac"                android:gravity="center_vertical" />

4、在主代码中调用:

pubdial = (ImageBtn)mActivity.findViewById(R.id.pub_dial);
pubdial.setTextViewText(R.string.dailButton);//设置文字pubdial.setImageResource(R.drawable.ico_dial);//设置图片

0 0
原创粉丝点击