2013-04-13 32 views
1

我试图在代码和java中设计。 这是活动的xml:如何部署Java和.XML?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" 
android:id="@+id/hello"> 

</RelativeLayout> 

这是Java代码,我想要。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello); 
    TextView txt=new TextView(this); 
    txt.setText("Hello World Problem"); 
    layout.addView(txt); 
    setContentView(R.layout.activity_main); 
} 

在相对布局中,我想在java代码中添加textview。但上面的java代码不起作用。错误:应用程序已不幸停止。我如何编码?

回答

2

R.id.hello不能被findViewById发现,直到您叫setContentView并添加R.id.hello你的活动的看法后。在findViewById以上移动setContentView

+0

哇。凉。愚蠢的我。天才你。感谢问:-)它的工作。 –

2

在使用findViewById()获取视图之前,您必须安排setContentView

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello); 

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
         (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT)); 

    TextView txt=new TextView(this); 
    txt.setLayoutParams(lp); 
    txt.setText("Hello World Problem"); 
    layout.addView(txt); 
} 
+0

谢谢你的回答。:-) –

1

当你在编码完全错误的,在运行时添加的TextView你必须做类似下面:

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

    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello); 
    TextView txt = new TextView(this); 
    txt.setText("Hello World"); 
    txt.setId(1); 
    txt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
    layout.addView(txt); 
+0

谢谢你的回答。 :-) –

1

你好RedHat_Father通过下面的代码替换Java代码,它可能有助于你:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 
    // Do not forget to set your layout file before you done the mapping of the elements 

    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello); 
    TextView txt=new TextView(this); 
    txt.setText("Hello World Problem"); 
    layout.addView(txt); 
} 

我希望因此这将工作... :)

+0

:-)完整的答案与完整的代码。谢谢。 –

+0

你是欢迎...:)... RedHat_Father 请接受答案...如果你真的发现它可以帮助你... :) –