view not attached to windows manager与This Toast was not created with Toast.makeText()

来源:互联网 发布:alpine python 编辑:程序博客网 时间:2024/06/07 17:53
public class Ex04_1Activity extends Activity {
   
EditText editText;
TextView textView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editText = (EditText) findViewById(R.id.myEditText);
        textView = (TextView) findViewById(R.id.myTextView);
        editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
textView.setText(editText.getText());
Toast toast = new Toast(Ex04_1Activity.this);
toast.setView(textView);//错误1
toast.show();
return false;
}
});
    }
}
错误1的地方会报view not attached to windows manager的错误。根据错误提示,将代码改为如下就可行了:
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
textView.setText(editText.getText());
Toast toast = new Toast(Ex04_1Activity.this);
TextView textView1 = new TextView(Ex04_1Activity.this);
textView1.setText(textView.getText());
toast.setView(textView1);
toast.show();
return false;
}
由此分析,以findViewById形式生成的View,new Toast()这种方式是拿不到的,因为初始程序还会报告一个FindViewLocked的错误。
为了进一步证明我的猜想,将代码改成如下形式:
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
textView.setText(editText.getText());
Toast.makeText(Ex04_1Activity.this, editText.getText(), 1).show();
return false;
}
程序又一次通过了。
再次改一下代码:
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
textView.setText(editText.getText());
Toast toast = new Toast(Ex04_1Activity.this);
    toast.setText(editText.getText().toString());
toast.show();
return false;
}
这时又报了一个:This Toast was not created with Toast.makeText()的错误。

由此可见,Toast.makeText()生成的Toast可以访问findViewById方式生成的View,而自己New Toast()的方式生成的Toast只能访问同样new 出来的View对象。原因大概是在.xml中生成的View对象可以被多个Activity引用,Android为了安全起见,就将其上了锁,并且提供唯一的Toast方式,Toast.makeText()来实现吐丝,这一点和单例模式颇有共同之处。
 
 
 
 
--------------------------------------------------------------------------------------------------------------下面是我自己遇到的问题,以及解决方案-------------------------------------------------------------------
在T.java(toast的操作类)中存在自定义Toast与系统Toast,而mToast对象为单例模式。
加入用完自定义Toast后没将mToast置空,当应用下次用系统Toast时则会报错:This Toast was not created with Toast.makeText()
我的解决方案就是每次用完自定义Toast,就将自定义Toast置空
0 0
原创粉丝点击