我有一個問題與方法findViewById()
,它在外面活動課使用時始終返回null,我知道我應該後setContentView(R.layout.activity_main)
的Android,NullPointerException異常
使用這種方法,但我該如何使用它在我的自定義按鈕,它是在xml中創建的?
對不起,我的英語不好,這是我的第一個問題在堆棧,阿門。 (下面的代碼示例)
<TextView
android:id="@+id/textBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<isen.mytestapl.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/myBtn"
android:layout_alignTop="@id/textBtn"
android:layout_margin="@dimen/activity_vertical_margin"/>
爲myButton類:
public class MyButton extends Button implements View.OnClickListener{
TextView textView;
public MyButton(Context context) {
super(context);
init();
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init(){
setOnClickListener(this);
}
@Override
public void onClick(View view) {
try
{
textView = (TextView) findViewById(R.id.textBtn);
textView.setText("It Works!");
}
catch (NullPointerException ex){
Log.d("MyLog","NullPointer");
}
}
}
您無法找到組件外部的視圖。 –
Srsly有沒有辦法使用PUBLIC STATIC來獲得這種觀點? – Isen
爲什麼不處理自定義按鈕單擊活動類? – user6650650