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

时间:2021-09-05 07:45:39
 
http://blog.sina.com.cn/s/blog_474928c90100x871.html
 
 
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()来实现吐丝,这一点和单例模式颇有共同之处