一个带图片和文字的按钮,效果图
1,Button的布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal" > <ImageView android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
2,自定义的控件
package com.exmple.custonbutton; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class ImgButton extends LinearLayout { private ImageView imageView; private TextView textView; public ImgButton(Context context) { super(context); // TODO Auto-generated constructor stub } public ImgButton(Context context, AttributeSet attrs) { super(context, attrs); //导入布局 LayoutInflater.from(context) .inflate(R.layout.img_text_button, this,true); imageView = (ImageView) findViewById(R.id.imageview); textView = (TextView) findViewById(R.id.textview); } public void setImageResource(int resId) { imageView.setImageResource(resId); } public void setTextContent(String content) { textView.setText(content); } }
3,使用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom" android:orientation="horizontal" > <com.exmple.custonbutton.ImgButton android:id="@+id/button_ok" android:layout_width="0dp" android:layout_height="50dp" android:layout_weight="1" android:background="@drawable/dialog_btn_selector" android:clickable="true" /> <com.exmple.custonbutton.ImgButton android:id="@+id/button_cancle" android:layout_width="0dp" android:layout_height="50dp" android:layout_weight="1" android:background="@drawable/dialog_btn_selector" android:clickable="true" /> </LinearLayout>
4,代码中控制界面
package com.exmple.custonbutton; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImgButton buttonok = (ImgButton) findViewById(R.id.button_ok); buttonok.setImageResource(R.drawable.save_nomal); buttonok.setTextContent("确定"); ImgButton buttonCancle = (ImgButton) findViewById(R.id.button_cancle); buttonCancle.setImageResource(R.drawable.cancel_nomal); buttonCancle.setTextContent("取消"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }