如何在java类中将TextView值作为字符串获取并设置它?
我认为xml代码不是必需的,但这里是如何在java类中将TextView值作为字符串获取并设置它?,java,android,xml,string,textview,Java,Android,Xml,String,Textview,我认为xml代码不是必需的,但这里是TextView: <TextView android:id="@+id/option4" android:layout_width="175dp" android:layout_height="120dp" android:background = "@drawable/rounded_corner" android:textAppearance="?android:textAppearanceLarge"
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类中option4Text的我的代码:
option4Text = (TextView)findViewById(R.id.option4);
option4Text.setText(wrongAnswer() + "");
其中,ErrorAnswer()只返回一个随机数。
我认为问题在于option4Text本身不是一个字符串,所以它没有值,调试后我发现在单击它之后,它不会进入if语句的内部。
所以我的问题是,如何获取为option4Text设置的文本并将其放入字符串中?
如何使用该字符串if语句。我不能清楚地理解您的问题。但据我所知,您只想从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的值。我无法清楚地理解您的问题。但据我所知,您只想从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()将给出TextView的值,该值通过Xml或java代码设置。这里的问题是,option4Text是一个对象,通过它您可以将字符串设置到TextView中,而不是获取,要获取TextView值,请使用一个Tehr字符串变量并获取如下值:
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 + "");
}
}
这里的问题是option4Text是一个对象,通过它您可以将字符串设置到TextView中,而不是获取,要获取TextView值,请使用一个TEHR字符串变量并获取如下值:
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 + "");
}
}
非常欢迎。再投票表决一下答案。所以这对其他人会有帮助。我做了,但我只有不到15次,没关系。只需享受编码:)非常欢迎。再投票表决一下答案。所以这对其他人会有帮助。我做了,但我只有不到15次,没关系。只需享受编码:)