Android studio手机软件设计基础(一)

本文介绍了在Android应用中如何通过XML和Java代码设置TextView的文本内容,提倡使用字符串资源来提高代码可维护性。作者展示了如何在XML中直接引用字符串资源以及在Java代码中动态获取并设置文本。
摘要由CSDN通过智能技术生成

简单控件分为文本显示,视图基础,常用布局,按钮触控,图像显示

文本显示

设置文本内容有两种方式:

(1)在xml文件中通过属性android:text设置文本

(2)在Java代码中通过文本视图对象的setText方法设置文本

通过xml设置文本,首先将文本宽和高都设置为包裹内容,设置文本为“你好,世界”,设置唯一标识tv_hello

<?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">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你好,世界"/>


</LinearLayout>

通过Java代码设置文本,首先继承于AppCompatActivity,然后重写onCreate方法,使用setContentView进行布局,通过唯一标识tv_hello,利用TextView类,使用setText进行文本设置

package com.example.chapter03;


import android.os.Bundle;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class text_view_activity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);
        findViewById(R.id.tv_hello);
        TextView tv_hello = findViewById(R.id.tv_hello);
        tv_hello.setText("你好,世界");
    }

但是在xml中的你好世界会出现出现一个警告Hardcoded string,这是它希望你能够把这个定义到我们的string.xml里面,而提示你的原因是你可能在布局文件中的很多个控件都会用到这个文本,当我们需要对这个文本进行修改时,可能需要多次修改,为了方便修改,我们最好引用一个字符串常量,所以我们在string.xml中定义一个常量

<resources>
    <string name="app_name">chapter 03</string>
    <string name="hello">你好,世界</string>
</resources>

那么上面的代码可以将你好,世界进行修改

<?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">

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


</LinearLayout>

在Java中可以修改为

package com.example.chapter03;


import android.os.Bundle;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class text_view_activity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);
        findViewById(R.id.tv_hello);
        TextView tv_hello = findViewById(R.id.tv_hello);
        tv_hello.setText(R.string.hello);
    }
}

运行结果如下图

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值