2011-06-22 64 views
0

我有一個奇怪的問題,我不明白...NullPointerException異常的setText()方法

我想從一個XML文件中做了PopupWindow:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/popup" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#404040" 
android:padding="15px"> 

<TextView android:id="@+id/popup_title" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:textColor="#ffffff" 
    android:textSize="16dip" 
    android:gravity="center_horizontal" /> 

</LinearLayout> 

,我只想做一個如此簡單的事情:在設置TextView的我的文字...這裏是我的代碼:

public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState);  

//UI 
ui = new RelativeLayout(this); 
ui.setBackgroundColor(Color.LTGRAY); 
setContentView(ui); 

//PopUp 
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
popUp = new PopupWindow(this); 
popUp.setContentView(inflater.inflate(R.layout.popup_piece, ui, false)); 


    //Boutton 
    bouton = new Button(this); 
    bouton.setText("POWPEUP"); 
    ui.addView(bouton); 

    bouton.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 

      popUp.showAtLocation(ui, Gravity.CENTER, 0, 0); 
      popUp.update(0, 0, 350, 400); 

      titrePopUp = (TextView)findViewById(R.id.popup_title); // THIS RETURNS NULL 
      Log.d("TextView", ""+titrePopUp); 
          //titrePopUp.setText("blop", TextView.BufferType.NORMAL); SO THIS DONT WORK 
     } 
    }); 
} 

說真的,我不明白爲什麼它返回NULL值..誰能幫助我,好嗎?

+0

其中有ü把'popup_piece'我沒有看到它在你的佈局.. – ngesh

回答

4

您正在搜索主佈局中的TextView,而不是PopupWindow。你需要做的這個代替:

titrePopUp = (TextView) popUp.getContentView().findViewById(R.id.popup_titre); 
+0

你是我的英雄,謝謝格雷厄姆。 – Greg

3

在佈局ID中拼寫爲popup_title,在代碼中拼寫爲popup_titre。也許,這是問題所在。

+0

好吧,這只是拷貝一個錯誤..我編程的法語和我翻譯它來問我的問題..真名是popup_titre – Greg

+0

@Greg好的。如果我理解你的意圖是正確的,你想在按鈕的點擊上顯示一個TextView。你爲什麼不使用Toasts?但是,你的方法是不正確的。初始化佈局時應該找到ViewById(),並在點擊按鈕時更改TextView的可見性。 – Egor

+0

我不使用吐司,因爲我的PopupWindow將包含一個ImageView和另一個TextView。順便說一下,我用格雷厄姆的回答找到了解決我的問題的方法。非常感謝您的幫助! – Greg

相關問題