【问题标题】:TextView in PopUpwindow cause NullPointer ExceptionPopUpwindow 中的 TextView 导致 NullPointer 异常
【发布时间】:2016-02-27 02:46:38
【问题描述】:

在弹出窗口中更改文本视图的文本时遇到问题。

简单版的代码如下所示:

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。

有人可以帮忙吗?

谢谢!

【问题讨论】:

  • 尝试使用tv_popup = (TextView) popupView.findViewById(R.id.tv_popup_text);...你在哪里初始化你的tv_popup

标签: android popup oncreate onstart


【解决方案1】:

清楚地看到您在带有布局的弹出窗口中使用 textview

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

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

试试这个

【讨论】:

  • 谢谢...工作正常。
【解决方案2】:

你必须用弹出对象初始化你的所有视图,所以你的代码应该是这样的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2020-08-18
    • 2018-04-07
    • 2014-01-31
    • 2011-09-11
    相关资源
    最近更新 更多