带图片(drawableXxx)的TextView:

在实际开发中,我们可能会遇到这种需求:

如图,要实现这种效果,可能你的想法是:一个ImageView用于显示图片 + 一个TextView用于显示文字,然后把他们丢到一个LinearLayout中,接着依次创建四个这样的小布局,再另外放到一个大的LinearLayout中,效果是可以实现,但是会不会有点繁琐呢?而且前面我们前面也说过,布局层次越少,性能越好!使用drawableXxx就可以省掉上面的过程,直接设置四个TextView就可以完成我们的需求!

基本用法:

设置图片的核心其实就是:drawableXxx;可以设置四个方向的图片:drawableTop(上),drawableButtom(下),drawableLeft(左),drawableRight(右)另外,你也可以使用drawablePadding来设置图片与文字间的间距!

效果图:(设置四个方向上的图片)

实现代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="com.jay.example.test.MainActivity" >  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerInParent="true"  
        android:drawableTop="@drawable/show1"  
        android:drawableLeft="@drawable/show1"  
        android:drawableRight="@drawable/show1"  
        android:drawableBottom="@drawable/show1"  
        android:drawablePadding="10dp"  
        android:text="张全蛋" />  
  
</RelativeLayout> 

一些问题:可能你会发现,我们这样设置的drawable并不能自行设置大小,在XML是无法直接设置的;所以我们需要在Java代码中来进行一个修改!

示例代码如下:

package com.jay.example.test;  
  
import android.app.Activity;  
import android.graphics.drawable.Drawable;  
import android.os.Bundle;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
    private TextView txtZQD;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        txtZQD = (TextView) findViewById(R.id.txtZQD);  
        Drawable[] drawable = txtZQD.getCompoundDrawables();  
        // 数组下表0~3,依次是:左上右下  
        drawable[1].setBounds(100, 0, 200, 200);  
        txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],  
                drawable[3]);  
    }  
} 

运行效果图:

代码分析:

  • ①Drawable[] drawable = txtZQD.getCompoundDrawables( );获得四个不同方向上的图片资源,数组元素依次是:左上右下的图片
  • ②drawable[1].setBounds(100, 0, 200, 200);接着获得资源后,可以调用setBounds设置左上右下坐标点,比如这里设置了代表的是:长是:从离文字最左边开始100dp处到200dp处宽是:从文字上方0dp处往上延伸200dp!
  • ③txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],drawable[3]);为TextView重新设置drawable数组!没有图片可以用null代替哦!PS:另外,从上面看出我们也可以直接在Java代码中调用setCompoundDrawables为TextView设置图片!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值