简单控件分为文本显示,视图基础,常用布局,按钮触控,图像显示
文本显示
设置文本内容有两种方式:
(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);
}
}
运行结果如下图