在xml textview中显示java字符串

时间:2016-12-29 06:25:34

标签: android xml string

这是我的以下java代码,问题是xml id。出于某种原因,每当我尝试将其打印出来时,我都会一直无效,这有什么不对吗?

public class MainActivity extends AppCompatActivity{

private boolean correct;
private String questionTxt;

public int correctAnswer()
{
    int first = (int)(Math.random() * 10);
    int second = (int)(Math.random() * 10);
    int answer = first + second;
    questionTxt = first + " + " + second;
    return answer;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

    TextView questionText = (TextView)findViewById(R.id.question);
    questionText.setText(questionTxt + "");
}

xml代码,只是常规textview:

 <TextView
    android:id="@+id/question"
    android:background="@color/colorAccent"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    android:layout_above="@+id/option1"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="11dp"
    android:screenOrientation="portrait"/>

2 个答案:

答案 0 :(得分:1)

调用此方法correctAnswer();在将值设置为textview之前

public class MainActivity extends AppCompatActivity{

private boolean correct;
private String questionTxt;

public int correctAnswer()
{   
int first = (int)(Math.random() * 10);
int second = (int)(Math.random() * 10);
int answer = first + second;
questionTxt = first + " + " + second;
return answer;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

correctAnswer();
TextView questionText = (TextView)findViewById(R.id.question);
questionText.setText(questionTxt + "");
}

答案 1 :(得分:0)

你应该在onCreate

之后移动方法
   public class MainActivity extends AppCompatActivity{

    private boolean correct;
    private String questionTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        TextView questionText = (TextView)findViewById(R.id.question);
        int answer = correctAnswer();
        questionText.setText(answer+");

    }

    public int correctAnswer()
    {
        int first = (int)(Math.random() * 10);
        int second = (int)(Math.random() * 10);
        int answer = first + second;
        questionTxt = first + " + " + second;
        return answer;
    }
 }