我不想用 string.xml 中的字符串值设置 TextView 的文本
所以我想在 java 类中使用 switch-case 来做到这一点
但它无法在我的 textView 上设置文本,当我运行应用程序时,textview 为空
抱歉,如果这是一个简单的愚蠢错误:)
这是我的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/shape">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textColor="@color/txt_dialog"
android:textSize="25sp"/>
</RelativeLayout>
这是string.xml
<resources>
<string name="t1"> hi </string>
<string name="t2"> hello </string>
<string name="t3"> ok </string>
</resources>
最后这是我的 java 代码,它应该选择随机选择的那些字符串之一,然后在对话框的 TextView 中设置它
public void hi (){
TextView txt_truth = (TextView) findViewById(R.id.textview);
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.mylayout);
Random random = new Random();
int hi_random = random.nextInt(2) + 1;
switch (hi_random){
case 1:
if (txt_truth != null) {
txt_truth.setText(getResources().getString(R.string.t1));
}
break;
case 2:
if (txt_truth != null) {
txt_truth.setText(getResources().getString(R.string.t2));}
break;
case 3:
if (txt_truth != null) {
txt_truth.setText(getResources().getString(R.string.t3));}
break;}
dialog.show();
}
最佳答案
您必须以这种方式从对话框 View 膨胀中获取 TextView 的 id
View view = LayoutInflater.from(this).inflate(R.layout.mylayout, null);
dialog.setContentView(view);
TextView txt_truth = (TextView) view.findViewById(R.id.textview);
关于java - 在 java 类中使用 string.xml 资源更改 textView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38356724/