2012-03-19 95 views
1

我想在我的應用程序中使用相對佈局。有兩個TextViews和一個Button。這裏是xml文件:Android相對佈局以編程方式更改TextView

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_height="fill_parent" 
android:layout_width="fill_parent" 
android:padding="30dip" 
android:orientation="vertical"> 


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

<TextView 
    android:id="@+id/level" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:layout_below="@id/up"/> 
    /> 

    <Button android:id="@+id/start" 
    android:text = "@string/go" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:layout_alignParentBottom="true" 
    /> 

    </RelativeLayout> 

現在,帶有id = up的TextView顯示完美。對於第二個TextView(id = level),我想通過我的java代碼向它添加文本。這是我做了什麼:

 TextView text = (TextView) findViewById(R.id.level); 
     text.setText("Hello Android"); 

但是,這崩潰的程序。我在這裏犯了什麼錯誤?

+0

你在哪裏執行該代碼?請記住,您必須在'setContentView'之後執行此操作。 – Cristian 2012-03-19 21:45:42

+0

該代碼應該是正確的,檢查eclipse debug中的錯誤消息日誌,看看哪一行代碼是問題 – 2012-03-19 21:47:11

+0

唉!我在setContentView之前執行它。謝謝@克里斯蒂安 – Jazib 2012-03-19 23:10:35

回答

1

原來是這樣......你必須總是使用findViewById之前調用setContentView

相關問題