我们知道,在android的实际开发过程中,TextView是一个非常常用的控件。有关TextView的基本属性我在这里就不再赘述了,这里主要整理下有关TextView的进阶应用。
**
一、利用Drawable属性为TextView添加图片
**
微信的这张图大家应该都不陌生,这张图的布局实现其实实现起来大家肯定首先会想到利用LiearLayout嵌套一个LinearLayout,,这样的实现方式感觉上的确挺简单的,但是,由于实际开发的过程中,会考虑到多重布局的会导致发布出来的应用的性能不好,所以一般采用Drawable方法,主要的属性是:drawableTop(上)、drawableButtom(下)、drawableLeft(左)、drawableRight(右),下面把我自己的丑代码粘出来。
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.dreamcreationman.androidstudy.MainActivity">
<TextView
android:id="@+id/text"
android:text="Android"
android:textSize="50sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@mipmap/ic_launcher"
android:drawableBottom="@mipmap/ic_launcher"
android:drawableLeft="@mipmap/ic_launcher"
android:drawableRight="@mipmap/ic_launcher"
android:drawablePadding="10dp"/>
</RelativeLayout>
不过不好意思的是这样的话在XML文件里不能设置图片的大小,只能在java代码里去控制:
java代码:
package com.example.dreamcreationman.androidstudy;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取textView
textView= (TextView) findViewById(R.id.text);
//新建一个Drawable数组来依次存放text从左(0),上(1),右(2),下(3)的图片
Drawable[] drawables=textView.getCompoundDrawables();
//举例修改上面的图,设置边界,代表的是: 长是:从离文字最左边开始100dp处到200dp处 宽是:从文字上方0dp处往上延伸200dp!
drawables[1].setBounds(100,100,200,200);
//再重新获取设置Drawable数组(刷新),没有就是Null
textView.setCompoundDrawables(drawables[0],drawables[1],drawables[2],drawables[3]);
}
}
酱紫就实现了微信上面的样式,也算是个小优化吧。
二、 使用autoLink属性识别链接类型
就在上面代码的基础上在布局文件里为TextView添加上一句android:autoLink=”phone”,就可以自动链接到相应的默认应用。对于这个autoLink属性里面包含phone(拨号),map(地图),email(邮件)等大家可以根据需要自行设置。all就是全部都包含,自动识别协议头~ 在Java代码中可以调用setAutoLinkMask(Linkify.ALL); 这个时候可以不写协议头,autolink会自动识别,但是还要为这个TextView设置: setMovementMethod(LinkMovementMethod.getInstance()); 不然点击了是没效果的!
欢迎在评论区留言指出错误,希望和大家一起进步!
谢谢观看。