2011-06-21 96 views
0

嗨,我是Android編程的新手,我試圖製作一個簡單的程序,通過單擊按鈕來更改文本。這裏是我的代碼:Android TextView

public class HelloAndroidActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     final Button button_scan = (Button) findViewById(R.id.button_scan); 

     button_scan.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       buttonBeenPressed(); 
     } 
     }); 

     } 

public void buttonBeenPressed(){ 

    final Button button_scan = (Button) findViewById(R.id.button_scan); 
    TextView tv_barcode = (TextView)findViewById(R.id.textview_barcode); 
    if (tv_barcode != null){ 
    tv_barcode.setText("been pressed."); 
    } else { 
     button_scan.setText("it's null dawg."); 
    } 
    } 
} 

我的XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <Button android:text="Scan" android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/button_scan"></Button> 
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="TextView" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textview_barcode"></TextView> 
</LinearLayout> 

但是TextView的是返回NULL,我不知道爲什麼。有什麼建議麼?謝謝。

回答

3

嗯,我沒有任何問題,你的代碼,運行沒有任何錯誤!你在使用eclipse嗎?然後嘗試清理你的項目。

+1

這奏效了,傻傻的Eclipse。謝謝。 –

1

看起來都是正確的,我....

調試這可能是在模擬器上或手機上運行你的應用程序和運行hierarchyviewer,找到你的TextView和檢查ID您最好的選擇。

0

您可以使用textview或按鈕。這裏是一個TextView一個例子,我已經從http://www.ahotbrew.com/android-textview-example/

<TextView 
    android:text="@string/textview_onclick" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/textview_onclick" 
    android:layout_below="@+id/textview_center" 
    android:textSize="25dp" 
    android:onClick="changeTextColor" 
    android:clickable="true"/> 

發現在您的MainActivity爲此

public void changeTextColor (View view) 
{ 
    TextView textView = (TextView) view.findViewById(R.id.textview_onclick); 
    textView.setText("newWord"); 
}