2013-09-26 24 views
-1

我想使用java代碼將Button添加到main_activity視圖,那麼我該怎麼做呢? 我已經嘗試過此代碼,不幸的是它沒有工作使用Java代碼在main_activity視圖中添加按鈕

public class MainActivity extends Activity { 

    Button btn; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     RelativeLayout l1 = ((RelativeLayout)this.findViewById(R.id.view1)); 
     btn = new Button(this); 
     btn.setText(R.string.hello_world); 
     l1.addView(btn); 
     setContentView(l1); 
    } 
} 
+2

在設置contentView之前,您無法調用'findViewById'。 – Ahmad

回答

2

正如艾哈邁德說,「設定內容查看之前,您不能調用findViewById」。這是因爲您的Views存在於您的layout之內,因此您需要用一個充氣的layout找到id英寸。請致電setContentView()先用layout其中包含view。然後,您可以找到view並將其添加到Button

@Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.your_layout); 
     RelativeLayout l1 = (RelativeLayout) findViewById(R.id.view1); 
     btn = new Button(this); 
     btn.setText(R.string.hello_world); 
     l1.addView(btn); 
    } 
+0

謝謝:)它正常工作:) –