码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-08-19 12:21:14      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:android   blog   http   os   ar   cti   div   代码   

 
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()来实现吐丝,这一点和单例模式颇有共同之处

view not attached to windows manager与This Toast was not created with Toast.makeText(),布布扣,bubuko.com

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

标签:android   blog   http   os   ar   cti   div   代码   

原文地址:http://www.cnblogs.com/qufanblog/p/3921524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!