2013-04-13 64 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 請接受答案...如果你真的發現它可以幫助你... :) –