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();
}
});
你可以發佈日誌嗎?我認爲這個錯誤是由'findViewById()'引起的,因爲你試圖在主要活動中找到id而不是在片段中 –
你必須在'onCreateView()'內部聲明和定義'OnClickListener',在'Fragment ',不在你的Activity的'onCreate()'裏面 – joao2fast4u