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

时间:2016-07-13 16:07:48

标签: 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();
}

4 个答案:

答案 0 :(得分:3)

你必须以这种方式从对话视图中获取textview的id

    View view = LayoutInflater.from(this).inflate(R.layout.mylayout, null);
    dialog.setContentView(view);
    TextView txt_truth = (TextView) view.findViewById(R.id.textview);

答案 1 :(得分:2)

  

它不能在我的textView上设置文本,当我运行应用程序时,textview   是空的

string.xml只有三个字符串要随机显示在TextView中,但您使用45获取随机数,该数字生成范围[0-45]+1中的数字。

获得1到3之间的数字:

int hi_random = random.nextInt(2) + 1;

答案 2 :(得分:0)

检查字符串资源的名称,是串联的a1还是t1

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(45) + 1;

switch (hi_random){
    case 1:
        if (txt_truth != null) {
            txt_truth.setText(getResources().getString(R.string.a1));
        }
        break;
    case 2:
        if (txt_truth != null) {
            txt_truth.setText(getResources().getString(R.string.a2));}
        break;
    case 3:
        if (txt_truth != null) {
            txt_truth.setText(getResources().getString(R.string.a3));}
        break;}
    dialog.show();
}

答案 3 :(得分:0)

在我的脑海中,我认为错误在于你的随机发生器。您已将上限值指定为45.

nextInt(int n)方法用于获取伪随机,均匀分布的int值,该值介于0(包括)和指定值(不包括)之间,从该随机数生成器的序列中提取。

int hi_random = random.nextInt(3) + 1;

请尝试使用上述代码并评论其是否有效。

您还可以在nextInt上查看java文档:nextInt javadoc