2015-02-07 73 views
0

我开始了一个空白项目,并通过添加下面的代码来修改了onCreate,但没有创建按钮,因为我在设计视图中看不到它。我做错了什么,我希望看到按钮的文本如所示。Android Studio onCreate setContentView

Button b = new Button(this); 
b.setText("Hello Button"); 
setContentView(b); 

许多THX

+0

你运行一个设备或模拟器上这个项目? AFAIK设计视图是基于xml的布局 – 2015-02-07 22:35:37

回答

0

因为要创建通过代码的布局,你不会看到它在XML视图。如果您构建并运行该应用程序,则应该看到出现Button

如果你宁愿看到XML鉴于Button,您应该修改main_layout.xml看起来像下面这样:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="I am a Button"/> 

</LinearLayout> 

您可以通过在Java代码中得到这个Button参考下面后的代码调用的setContentView():

Button button = (Button) findViewById(R.id.button);