setText显示字符串
1、如何实现
(1)activity_main.xml文件里,点击右上角的【Code】切换为代码编写页面
(2)添加布局代码
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"
/>
(3)MainActivity.java文件里添加代码
String temp="hey,guy,what's up?";
TextView tv=findViewById(R.id.tv); //获取id
tv.setText(temp);
2、两次使用setText闪退的原因
(1)没有寻找id,也就是直接
TextView tv;
然后一运行就闪退
(2)不小心把下面的语句注释掉了
setContentView(R.layout.activity_main);
然后运行到setText就闪退
3、运行结果
💜附上整个代码:
//MainActivity.Java文件
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String temp="hey,guy,what's up?";
TextView tv=findViewById(R.id.tv); //获取id
tv.setText(temp);
}
}
//activity_main.xml文件里
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:id="@+id/tv"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>