2012-11-02 220 views
1

嘿傢伙需要一點幫助........我的意圖是開發一個只包含一個按鈕的應用程序......並點擊它,它必須在屏幕上動態創建另一個按鈕.. .....動態創建按鈕

這裏是我的代碼...

 public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Button bee=new Button(getBaseContext()); 
      bee.setText("hello:"); 
      RelativeLayout a; 
      a=(RelativeLayout)findViewById(R.layout.activity_main); 
    a.addView(bee,new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
     } 
    }); 

這個代碼是免費的錯誤,但在執行時說:「不幸的是‘MyApplication的’已停止」 ......

請做幫助傢伙..(我唯一的目標是動態創建窗口小部件,因此嘗試DIS程序)。如果你有任何其他建議請發表評論

+3

歡迎來到SO。請查看logcat中的堆棧跟蹤並將其發佈到您的問題中。 – nhaarman

+1

查看「logcat」,查看應用程序崩潰的原因。 –

+1

歡迎來到stackoverflow ..請注意這些事情1)當你發佈一個問題,請確保它的標題是有效的。 android開發者(beginer)不是其中之一。 2)如果你碰到了,你需要發佈的最重要的東西就是崩潰日誌 – Krishnabhadra

回答

1
a=(RelativeLayout)findViewById(R.layout.activity_main); 

activity_main是佈局,而不是RelativeLayout小部件!

你應該使用

a=(RelativeLayout)findViewById(R.id.my_relative_layout); 

請張貼堆棧跟蹤(logcat的),所以你會得到更好更快的答案。

0

您正試圖「找到」一個不存在的佈局!請確保您有一個有效的ID定義的RealtiveLayout然後執行

a=(RelativeLayout)findViewById(R.layout.activity_main);

0

a=(RelativeLayout)findViewById(R.id.valid_layout_id);

,而不是嘗試。

RelativeLayout rLayout = (RelativeLayout)findViewById(R.id.relativeLayout); // Here this should be id of your relative layout. 
Button btn = new Button(this); 
rLayout.addView(btn); 
0

您發現ID而不是佈局

所以改變這一行:

a=(RelativeLayout)findViewById(R.id.activity_main); 
0

嘗試用這個代碼,我覺得你越來越沒有正確設置參數,以便檢查只是因爲問題用此代碼 -

LinearLayout container = (LinearLayout)findViewById(R.id.container); 

    Button btn = new Button(this); 
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, 
     LinearLayout.LayoutParams.WRAP_CONTENT); 
    btn.setLayoutParams(lp); 

    container.addView(btn);