2011-01-22 19 views
21

我正在開發一個android程序。用戶點擊一個按鈕,我做了一些數學計算,我想在一些TextView對象中更改我在視圖中的值。有人可以告訴我如何在我的代碼中做到這一點?如何更改Java代碼中的TextView值?

回答

39

我相信,這問題是this one的延續。

你想做什麼?你真的想在用戶點擊一個按鈕時動態改變TextView對象中的文本嗎?你當然可以這樣做,如果你有一個原因,但是,如果文本是靜態的,它通常是在main.xml中文件中設置,如下所示:

<TextView 
android:id="@+id/rate" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/rate" 
/> 

字符串「@字符串/率」是指要在strings.xml文件看起來像這樣的條目:

<string name="rate">Rate</string> 

如果你真的想要在以後改變這個文本,您可以通過使用尼古拉的例子這樣做 - 你會得到通過向TextView的參考利用在main.xml中定義的id,像這樣:


final TextView textViewToChange = (TextView) findViewById(R.id.rate); 
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button."); 
13

首先,我們需要找到一個Button

Button mButton = (Button) findViewById(R.id.my_button); 

在這之後,你必須實現View.OnClickListener有你應該找到TextView和執行方法setText

mButton.setOnClickListener(new View.OnClickListener { 
    public void onClick(View v) { 
     final TextView mTextView = (TextView) findViewById(R.id.my_text_view); 
     mTextView.setText("Some Text"); 
    } 
});