由于SDK提供的ImageButton只能添加图片,不能添加文字;而Button控件添加的文字只能显示在图片内部;当我们需要添加文字在图片外部时就不能满足我们的需求了,顾只能自己写个自定义ImageButton。说是ImageButton,其实并不是继承于ImageButton,而是从LinearLayout继承,由于LinearLayout是线性排列,通过setOrientation(LinearLayout.VERTICAL)的方式达到View垂直排列的目的,所以很简单,只需要添加两个View:一个ImageView和一个TextView即可。代码如下:
package com.example.adtest; import android.content.Context;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView; public class ImageButtonEx extends LinearLayout { private ImageView _imageView = null;
private TextView _textView = null; public ImageButtonEx(Context context){
super(context);
} public ImageButtonEx(Context context, int imageResId, int textResId) {
super(context);
// TODO Auto-generated constructor stub _imageView = new ImageView(context);
_textView = new TextView(context); _imageView.setImageResource(imageResId);
_textView.setText(textResId); _imageView.setPadding(0, 0, 0, 0);
_textView.setPadding(0, 0, 0, 0); setClickable(true);
setFocusable(true);
setBackgroundResource(android.R.drawable.btn_default);
setOrientation(LinearLayout.VERTICAL); addView(_imageView);
addView(_textView);
} public void setBtnText(CharSequence text)
{
_textView.setText(text);
} }
添加一个LinearLayout作为ImageButtonEx的容器。
<LinearLayout
android:id="@+id/llImageBtnEx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
然后再Activity中添加调用代码:
package com.example.adtest; import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout; public class MainActivity extends ActionBarActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); final ImageButtonEx imageBtnEx = new ImageButtonEx(this, R.drawable.icon, R.string.hello_world); imageBtnEx.setOnClickListener(new Button.OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
imageBtnEx.setBtnText("已经点击过了");
}}); LinearLayout llimageBtnEx = (LinearLayout)findViewById(R.id.llImageBtnEx);
llimageBtnEx.addView(imageBtnEx); } }