[转载]http://bbs.51cto.com/thread-912435-1.html
自定义Android带图片的按钮
http://blog.csdn.net/lzx_bupt/article/details/5600187
package com.billhoo.study;
import android.content.Context;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
//自定义ImageButton,模拟ImageButton,并在其下方显示文字
//提供Button的部分接口
public
class MyImageButton extends LinearLayout {
public MyImageButton(Context context, int imageResId, int textResId) {
super(context);
mButtonImage = new ImageView(context);
mButtonText = new TextView(context);
setImageResource(imageResId);
mButtonImage.setPadding(0, 0, 0, 0);
setText(textResId);
setTextColor(0xFF000000);
mButtonText.setPadding(0, 0, 0, 0);
//设置本布局的属性
setClickable(true); //可点击
setFocusable(true); //可聚焦
setBackgroundResource(android.R.drawable.btn_default); //布局才用普通按钮的背景
setOrientation(LinearLayout.VERTICAL); //垂直布局
//首先添加Image,然后才添加Text
//添加顺序将会影响布局效果
addView(mButtonImage);
addView(mButtonText);
}
// ----------------public method-----------------------------
/*
* setImageResource方法
*/
public
void setImageResource(int resId) {
mButtonImage.setImageResource(resId);
}
/*
* setText方法
*/
public
void setText(int resId) {
mButtonText.setText(resId);
}
public
void setText(CharSequence buttonText) {
mButtonText.setText(buttonText);
}
/*
* setTextColor方法
*/
public
void setTextColor(int color) {
mButtonText.setTextColor(color);
}
// ----------------private attribute-----------------------------
private ImageView mButtonImage = null;
private TextView mButtonText = null;
}
<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
androidrientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 这就是我们的“数据管理按钮” -->
<LinearLayout
android:id="@+id/ll_bt_data_config"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
package com.billhoo.study;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public
class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btDataConfig = new MyImageButton(this, R.drawable.option, R.string.text);
//获取包裹本按钮的容器
llbtDataConfig = (LinearLayout) findViewById(R.id.ll_bt_data_config);
//将我们自定义的Button添加进这个容器
llbtDataConfig.addView(btDataConfig);
//设置按钮的监听
btDataConfig.setOnClickListener(new Button.OnClickListener() {
@Override
public
void onClick(View v) {
btDataConfig.setText("按钮被点击过了");
}
});
}
private LinearLayout llbtDataConfig = null; //main布局中包裹本按钮的容器
private MyImageButton btDataConfig = null;
}
文字在左中位置