2014-12-28 50 views
0

我有一個按鈕,我試圖聽,但該按鈕不在屏幕上。我使用的片段很多,我想要聽的按鈕一開始並沒有出現在屏幕上,所以當我啓動應用程序時,它立即崩潰。我在想,因爲它不在屏幕上,而且它試圖聽那些不在那裏的東西,它開始崩潰。我該如何使用它,以便在按鈕出現在屏幕上時,按鈕可以開始收聽?在點擊監聽器上設置按鈕之前,它是在屏幕上?

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // This button is not in the main fragment 
    Button akbutton = (Button) findViewById(R.id.akbutton); 

    akbutton.setOnClickListener(new View.OnClickListener() { 
     FragmentManager fragmentManager = getFragmentManager(); 
     Fragment fragment = null; 
     public void onClick(View v) { 
      fragment = new ak47(); 
      fragmentManager.beginTransaction() 
        .replace(R.id.container, ak47.newInstance(0)) 
        .commit(); 
     } 
    }); 
+0

你可以發佈日誌嗎?我認爲這個錯誤是由'findViewById()'引起的,因爲你試圖在主要活動中找到id而不是在片段中 –

+0

你必須在'onCreateView()'內部聲明和定義'OnClickListener',在'Fragment ',不在你的Activity的'onCreate()'裏面 – joao2fast4u

回答

0

確定的主要問題是什麼,你找到你的按鈕的視圖裏面沒有你的地方設置它在Listener.So請聲明它,它應該與你的Listener.Second解決方案中使用的添加單個行到你的尋找按鈕的視圖主要是這個詞finalstatic或這兩個final static一般你的代碼必須看起來像這樣。 final Button akbutton = (Button) findViewById(R.id.akbutton);您可以將final更改爲我上面寫的變量。

相關問題