PopUpwindow 中的 TextView 导致 NullPointer Exception

TextView in PopUpwindow cause NullPointer Exception

在 PopUp Window 中更改文本视图的文本时遇到问题。

代码的简单版本如下所示:

public class Activity extends Activity {


View popupView;
PopupWindow pw_info;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_menue);



    // Layout components
    tv_function = (TextView) findViewById(R.id.function);
    tv_result = (TextView) findViewById(R.id.tv_result);
    tv_total = (TextView) findViewById(R.id.tv_total_result);

    });



@Override
protected void onStart(){
    super.onStart();
    pop_up();
}



// PopUp Window for start and end
private void pop_up(){

    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
    popupView = layoutInflater.inflate(R.layout.popup_window, null);
    final PopupWindow pw_popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);


    popupView.post(new Runnable() {
        public void run() {
            pw_popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
            tv_function.setText("start");
            tv_popup = (TextView) findViewById(R.id.tv_popup_text);


            new CountDownTimer(3000, 1000) {

                public void onTick(long l_millisUntilFinished) {
                    // Problem: accessing tv_popup creates NULLPOINTER Exception!
                    tv_popup.setText(String.valueOf(l_millisUntilFinished / 1000));
                }

                public void onFinish() {
                    pw_popupWindow.dismiss();
                                  }

            }.start();


            }
    });

}

我尝试在每次倒计时时更改 TextView。我的问题是我无法在 CountDownTimer 期间更改 TextView。这会导致 NullPointer 异常。 我不太确定何时定义和初始化 tv_popup TextView。

有人能帮忙吗?

谢谢!

清楚地看到您在 pop window 中使用带有布局

的 textview

所以你需要在定义它的ID时添加popupView对象

 tv_popup = (TextView) popupView.findViewById(R.id.tv_popup_text);

试试这个

您必须使用弹出对象初始化所有视图,因此您的代码应该像

tv_popup = (TextView) popupView.findViewById(R.id.tv_popup_text);