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

來源:互聯網
上載者:User

標籤: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() {@Overridepublic boolean onKey(View arg0, int arg1, KeyEvent arg2) {textView.setText(editText.getText());Toast toast = new Toast(Ex04_1Activity.this);toast.setView(textView);//錯誤1toast.show();return false;}});    }}錯誤1的地方會報view not attached to windows manager的錯誤。根據錯誤提示,將代碼改為如下就可行了:@Overridepublic 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()來實現吐絲,這一點和單例模式頗有共同之處

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.