1 .android的ImageButton标签是没有text属性的,那么我们要在一个ImageButton里放置文字怎么办呢?
先上效果图如下:
如果我们不设置背景效果如下:但是给人的感觉就行分离的两个组件:
我们可以继承LinearLayout自定义标签:ImageButton_define.java
package com.test;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ImageButton_define extends LinearLayout {
private ImageView imageViewbutton;
private TextView textView;
public ImageButton_define(Context context,AttributeSet attrs) {
super(context,attrs);
// TODO Auto-generated constructor stub
imageViewbutton = new ImageView(context, attrs);
imageViewbutton.setPadding(0, 0, 0, 0);
textView =new TextView(context, attrs);
//水平居中
textView.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
textView.setPadding(0, 0, 0, 0);
setClickable(true);
setFocusable(true);
setBackgroundResource(android.R.drawable.btn_default);
setOrientation(LinearLayout.VERTICAL);
addView(imageViewbutton);
addView(textView);
}
}
2。接下来定义布局文件:
这个不就文件使用的标签就是我们上面自定义的标签:如下:text.xml
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:id="@+id/define_iamgebutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/android"
android:background="#00000000"
android:text="图片文本"
android:textColor="#cc0000"
>
之后我们定义个activity,引入我们定义的布局文件资源:ImageButton_de.java
package com.test;
import android.app.Activity;
import android.os.Bundle;
public class ImageButton_de extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
}
方法二:
定义布局文件:
android:id="@+id/button_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标题"
android:drawableLeft="@drawable/android"
/>
运行效果: