TextView的主要作用:显示文本信息。

TextView的基本属性:

android:id  控件唯一标识
android:text  显示的文本信息
android:layout_width  控件宽度
android:layout_height  控件高度

宽度和高度的取值:

layout_width&layout_height的属性值:
--可设置固定的值:100dp
--可根据内容动态变化:wrap_content
--可适配父布局的宽和高:match_parent/fill_parent[2.3版本之前为fill_parent]

Android中的度量单位:

dp|dip:设备独立像素,与像素密度密切相关,可以根据屏幕密度自行转换。
sp:与缩放无关的抽象元素,主要用于字体显示。
px:即像素,表示屏幕上物理像素点。在画表格线、阴影线等类似情况下建议使用,其余情况不建议使用。

有关dp和dpi的补充知识:

dpi(像素密度):
--Dots Per Inch(每英寸所打印的点数)的缩写
--标准屏幕dpi:160(1英寸上有160个点)
dp:
--在标准dpi的前提下,1个像素点的长度:1dp=1px
--在dpi=320的前提下:1dp=2px;
总结:
--使用dp做单位:不同的dpi屏幕看起来一样长
--使用px做单位:dpi越高的屏幕,看起来越短

Android中资源文件的引用:

@+id:
--在R.java中添加一个新的资源id
--除此之外还有@id,其表示引用现有的id资源
@string:
--@string/hello_world表示引用name为"hello_world"的string标签的字符串

常用的资源标签类型:

string:字符串
color:颜色
style:样式
dimen:尺寸

示例:

<TextView
    android:id="@+id/tv_show"
    android:text="@string/content_title"
    android:textColor="@color/colorGreen"
    android:textSize="@dimen/title"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>    

控件对象的获取方法:

获取TextView对象:
    --通过findViewById(控件id)方法
    --此方法返回一个View对象,需要强制类型转换
    --View类是所有UI类控件的基类
获取属性值:
    --记忆方法:get+属性名称
    --示例:
        ** textView.getText()获取android:text属性值
        ** textView.getTextSize()获取android:textSize属性值
设置属性值:
    --记忆方法:set+属性名称
    --示例:
        ** textView.setText("显示文本信息")设置android:text
        ** textView.setTextSize(40.0f)设置android:textSize

示例:

package com.example.cerizo;

import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        // 获取TextView对象
        TextView tv_show = findViewById(R.id.tv_show);

        // 获取文本内容
        String text = tv_show.getText().toString();

        Log.i("lhj",text);
        // 吐司
        Toast.makeText(this,text,Toast.LENGTH_SHORT).show();

        // 设定文本的内容
//        tv_show.setText("hello jasmyn");
        tv_show.setText(getResources().getString(R.string.content));
        tv_show.setTextColor(getResources().getColor(R.color.colorBlue));

    }
}

总结:

使用TextView显示文本信息
在resources标签下可以定义常量标签
通过findViewById()方法获取控件对象,此方法返回的是一个View对象,需要强制类型转换
获取某个控件对象之前,一定要引用相应的布局
动态获取资源常量值需要获取Resources对象,Resources对象通过getResources()获得
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐