2011-02-19 102 views
1

我的活動中有一半屏幕自定義視圖和一個TextView。在自定義視圖中更新TextView

<com.sted.test.mainView 
    android:id="@+id/mainView" android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 

<TextView android:id="@+id/tvScore" android:layout_height="wrap_content" android:layout_width="wrap_content" 
    android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" /> 

在點擊自定義視圖,我怎麼可以更新我的活動TextView的?

目前我在我的自定義視圖的onTouchEvent()中有這段代碼,但它在setText()部分中遇到了NullPointerException。我應該永遠不更新我的自定義視圖中的TextView嗎?

TextView tvScore = (TextView) findViewById(R.id.tvScore); 
tvScore.setText("Updated!"); 
+0

檢查你的setContentView在哪裏給出了正確的佈局,還有在給出setText之前,你必須聲明該textview,如果你做了所有這些事情,那麼在這部分代碼錯誤的錯誤是在這個代碼之外 –

回答

4

您無法在自定義視圖的代碼中「查看」TextView tvScore。 findViewById()從您調用它的視圖開始查找層次結構中的視圖,如果您調用Activity.findViewById()(當然這僅在setContentView()後才起作用),則查看層次結構根。

如果您的自定義視圖是複合視圖,比如說包含一些TextView的線性佈局,那麼在那裏使用findViewById()會很有意義。

解決方法是找到例如onCreate()中的textview,然後以某種方式將它傳遞到自定義視圖(如某些set..()方法)。

編輯

如果您的自定義視圖,您有類似:

public class CustomView extends View { 
    ... 
    TextView tvToUpdate; 
    public void setTvToUpdate(TextView tv) { 
     tvToUpdate = tv; 
    } 
    ... 
} 

,你可以這樣做:

protected void onCreate(Bundle bundle) { 
    ... 
    CustomView cv = (CustomView) findViewById(R.id.customview); 
    TextView tv = (TextView) findViewById(R.id.tv); 
    cv.setTvToUpdate(tv); 
    ... 
} 

所以,自那之後,你將有一個參考到自定義視圖代碼中的textview。這就像某種設置。

+0

Can你詳細說明如何通過set ..()方法將textview傳遞給自定義視圖?謝謝 – SteD

+0

@SteD編輯答案 – bigstones

+0

非常感謝!那訣竅:) – SteD

相關問題