项目中的需求往往十分怪异,例如在按钮文字的左边加一个图标,这样按钮内部既有文字又有图片,乍看之下Button和ImageView都没法直接使用,若用LinearLayout对ImageView和Button组合布局,这样固然可行,但是布局文件会冗长许多
其实有一个既简单又灵活的办法,在文字周围放置图片,只使用Button就能实现,具体可在XML布局文件中设置一下5个属性
drawableTop : 指定文本上方的图形
drawableBottom : 指定文本下方的图形
drawableLeft : 指定文本左边的图形
drawableRight : 指定文本右边的图形
drawablePadding : 指定图形与文本的间距
示例:
<Button
android:id="@+id/btn_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@mipmap/ic_launcher"
android:text="程序员"/>
若在代码中实现,则课调用如下方法
setCompoundDrawables : 设置文本周围图形的位置,接受四个参数,可分别设置为左边、上边、右边、下边的图形
setCompoundDrawablePadding : 设置图形与文本的间距
下面的代码演示在按钮中变换图标位置的功能
XML布局如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="sxpi.com.myapplication.MainActivity">
<Button
android:id="@+id/btn_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="程序员" />
<Button
android:id="@+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图标在左" />
<Button
android:id="@+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图片在右" />
<Button
android:id="@+id/top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图片在上" />
<Button
android:id="@+id/bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图片在下" />
</LinearLayout>
程序如下
import android.graphics.drawable.Drawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_icon;
private Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_icon=(Button)findViewById(R.id.btn_icon);
drawable=getResources().getDrawable(R.mipmap.ic_launcher);
//必须设置图片大小,否则不显示图片
drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
findViewById(R.id.left).setOnClickListener(this);
findViewById(R.id.right).setOnClickListener(this);
findViewById(R.id.top).setOnClickListener(this);
findViewById(R.id.bottom).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId()==R.id.left){
btn_icon.setCompoundDrawables(drawable,null,null,null);
}else if (v.getId()==R.id.top){
btn_icon.setCompoundDrawables(null,drawable,null,null);
}else if (v.getId()==R.id.right){
btn_icon.setCompoundDrawables(null,null,drawable,null);
}else if (v.getId()==R.id.bottom){
btn_icon.setCompoundDrawables(null,null,null,drawable);
}
}
}