java - 在 java 类中使用 string.xml 资源更改 textView

标签 java android xml

我不想用 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/

相关文章:

xml - 无法使用WSL将第二个节点加入Apache Ignite集群

java - 将 `java.sql.blob` 转换为 `javax.xml.transform.stream.StreamSource`

javascript - 仅使用 Javascript 读取 XML 文件

java - 使用musicg库在android中创建频谱图

java - Hashmap 中一个键的多个值

java - 将 java.util.logging 写入文件

java - 如何在nexus7上解压代码

安卓应用 : How to create a new window?

android - ConstraintLayout 中两个 Layout 之间的 ScrollView

java - Bash 脚本中的 NoClassDefFoundError