【问题标题】:How do I get the TextView value as string in java class and set it?如何在 java 类中获取 TextView 值作为字符串并设置它?
【发布时间】:2016-12-30 03:47:41
【问题描述】:

我不认为xml代码是必要的,但这里是TextView

<TextView
    android:id="@+id/option4"
    android:layout_width="175dp"
    android:layout_height="120dp"
    android:background = "@drawable/rounded_corner"
    android:textAppearance="?android:textAppearanceLarge"
    android:gravity="center"
    android:text="option 4"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/option3"
    android:layout_toEndOf="@+id/option3"
    android:screenOrientation="portrait"
    android:onClick="onClick4"
    android:clickable="true"/>

最后两行是检测点击的内容。

我的 java 代码是:

public void onClick4(View v) {
    if (option4Text.equals(Integer.toString(answer))) {
        TextView questionText = (TextView) findViewById(R.id.question);
        correctAnswer();
        questionText.setText(questionTxt + "");
    }
}

java 类中 option4Text 的代码:

option4Text = (TextView)findViewById(R.id.option4);
    option4Text.setText(wrongAnswer() + "");

其中 wrongAnswer() 只返回一个随机数。 我认为问题在于 option4Text 本身不是字符串,因此它没有值,经过调试我发现单击后它不会进入 if 语句内部。 所以我的问题是,如何获取我为 option4Text 设置的文本并将其放入字符串中? 如果 if 语句使用该字符串的方法是什么。

【问题讨论】:

    标签: java android xml string textview


    【解决方案1】:

    我无法清楚地理解您的问题。但据我了解,您只想从 xml 文件中获取 TextView 的字符串值。

    如我所见,您犯了一些错误。 option4Text 是 TextView 的一个对象。因此,要获取它的字符串值,请使用以下代码。

    public void onClick4(View v) 
    {
        if (option4Text.getText().toString().equals(toString(answer))) {
            TextView questionText = (TextView) findViewById(R.id.question);
            correctAnswer();
            questionText.setText(questionTxt + "");
        }
    }
    

    option4Text.getText().toString() 将给出通过 Xml 或 java 代码设置的 TextView 的值。

    【讨论】:

    • 非常欢迎。也只是赞成答案。以便对其他人有所帮助。
    • 我做到了,但我的代表次数少于 15 个 XD
    • 没关系。只是享受编码:)
    【解决方案2】:

    这里的问题是 option4Text 是您将字符串设置到 TextView 而不是获取的对象,要获取 TextView 值,请使用 anotehr String 变量并获取如下值:

    String option4str;// take as global variable
    option4Text = (TextView)findViewById(R.id.option4);
    option4Text.setText(wrongAnswer() + "");
    option4str = option4Text.getText().toString();
    

    然后像这样匹配:

    public void onClick4(View v) {
        if (option4str .equals(Integer.toString(answer))) {
            TextView questionText = (TextView) findViewById(R.id.question);
            correctAnswer();
            questionText.setText(questionTxt + "");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多