Android 基础知识4-3.1 TextView(文本框)详解

导读:本篇文章讲解 Android 基础知识4-3.1 TextView(文本框)详解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、前言

       TextView就是一个显示文本标签的控件,就是用来显示文本。可以在代码或者 XML中设置字体,字体大小,字体颜色 ,字体样式 (加粗级斜体),文字截断(比如:只显示10个字,多余的显示三个点),显示多行,最多显示多少行等。

二、TextView讲解

Android 基础知识4-3.1 TextView(文本框)详解

1.示例1在代码中定义TetxView样式

activity类中代码:
public class TextViewActivity implements AppCompatActivity {
    // 声明TetxView对象
    private TextView textView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_textview);

        // 获得TextView对象
        textView = findViewById(R.id.txtOne);
        String string = "TextView示例,欢迎使用!"
        // 设置文本颜色
        textView.setTextColor(Color.RED);
        // 设置字体大小
        textView.setTextSize(20);
        // 设置文字背景
        textView.setBackgroundColor(Color.BLUE);
        // 设置TetxView显示的文字
        textView.setText(string);

    }
}

XML文件:

<TextView
    android:id="@+id/txtOne"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"/>

2.示例2,在xml文件中定义TetxView样式

XMl文件:
<TextView
    android:id="@+id/txtOne"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="#8fffad"
    android:gravity="center"
    android:text="TextView(显示框)"
    android:textColor="#EA5246"
    android:textSize="18sp"
    android:textStyle="bold|italic" />

三、属性说明

id:为TextView设置一个组件id,根据id,我们可以在Java代码中通过findViewById()的方法获取到该对象,然后进行相关属性的设置,又或者使用RelativeLayout时,参考组件用的也是id!
layout_width:组件的宽度,一般写:wrap_content或者match_parent(fill_parent),前者是控件显示的内容多大,控件就多大,而后者会填满该控件所在的父容器;当然也可以设置成特定的大小,比如我这里为了显示效果,设置成了200dp。
layout_height:组件的宽度,内容同上。
gravity:设置控件中内容的对齐方向,TextView中是文字,ImageView中是图片等等。
text:设置显示的文本内容,一般我们是把字符串写到string.xml文件中,然后通过@String/xxx取得对应的字符串内容的,这里为了方便我直接就写到”“里,不建议这样写!!!
textColor:设置字体颜色,同上,通过colors.xml资源来引用,别直接这样写!
textStyle:设置字体风格,三个可选值:normal(无效果),bold(加粗),italic(斜体)
textSize:字体大小,单位一般是用sp!
background:控件的背景颜色,可以理解为填充整个控件的颜色,可以是图片哦!

下面是几个常用的方法在布局中定义的参数,如下表所示:

TextView对象方法 xml属性
setTextColor android:textColor
setTextSize android:textSize
setText android:text
setBackgroundResoure android:background
setHeight/setWidth android:height/android:width

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/119099.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!