想要在文字周围放置图片,使用TextView就能实现。
1.具体可在XML布局文件中设置以下5个属性:
-
drawableTop:指定文本上方的图形。
-
drawableBottom:指定文本下方的图形。
-
drawableLeft:指定文本左边的图形。
-
drawableRight:指定文本右边的图形。
-
drawablePadding:指定图形与文本的间距。
2.在代码中实现,则可以调用如下方法
-
setCompoundDrawables:设置文本周围的图形。可分别设置左边、上边、右边、下边的图形。
-
setCompoundDrawablePadding:设置图形与文本的间距。
3.代码演示点击按钮设置不同位置的图标
XML文件中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="热烈欢迎"
android:gravity="center"/>
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/bt1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="图标在左"
android:gravity="center"/>
<Button
android:id="@+id/bt2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="图标在上"
android:gravity="center"/>
<Button
android:id="@+id/bt3"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="图标在右"
android:gravity="center"/>
<Button
android:id="@+id/bt4"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="图标在下"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
java代码中
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView tv;
private Button bt1;
private Button bt2;
private Button bt3;
private Button bt4;
private Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
bt1 = findViewById(R.id.bt1);
bt2 = findViewById(R.id.bt2);
bt3 = findViewById(R.id.bt3);
bt4 = findViewById(R.id.bt4);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
drawable = getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bt1:
tv.setCompoundDrawables(drawable,null,null,null);
break;
case R.id.bt2:
tv.setCompoundDrawables(null,drawable,null,null);
break;
case R.id.bt3:
tv.setCompoundDrawables(null,null,drawable,null);
break;
case R.id.bt4:
tv.setCompoundDrawables(null,null,null,drawable);
break;
}
}
}
?