2014-01-12 95 views
0

好的,我遵循developer.android.com上的Android教程來構建我的第一個應用程序。因此,爲了創建一個簡單的用戶界面,我在教程中添加了一個按鈕和文本字段。但是當我在手機上運行它時,我看不到按鈕或文本字段。無法將按鈕和文本字段添加到我的Android應用程序

package com.example.lookforbuttons; 
    import android.os.Bundle; 
    import android.app.Activity; 
    import android.view.Menu; 
    import android.widget.TextView; 

    public class MainActivity extends Activity { 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 

      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

      TextView tv= new TextView(this); 
      tv.setText("Buttons"); 
      setContentView(tv); 
     } 
    } 

.xml文件,我描述的佈局是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout 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:orientation="horizontal"> 
     <EditText android:id="@+id/edit_message" 
      android:layout_weight="1" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:hint="@string/edit_message" /> 
     <Button android:id="@+id/send" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/button_send" /> 
    </LinearLayout> 

和strings.xml中看起來是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
    <resources> 
     <string name="app_name">Buttons</string> 
     <string name="edit_message">Enter a message</string> 
     <string name="button_send">Send</string> 
     <string name="action_settings">Settings</string> 
     <string name="title_activity_main">MainActivity</string> 
    </resources> 

目標Android版本是4.03,因爲我我正在4.03手機上進行測試。當我運行這個我只打印「按鈕」,沒有按鈕或文本字段。謝謝。

回答

0

您撥打setContentView兩次。當你這樣做時,第二次是你將在屏幕上看到的內容,因爲它會覆蓋你在setContentView()的第一個電話中調用的任何layout。所以,既然你打電話

setContentView(tv); 

最後你只有TextView。刪除該行,你應該看到你的EditText和你的Button

0

在您的代碼中,您將設置setContentview()兩次。這意味着您正在更改layout,其中包含ButtonTextView以及第二個setContentview()。 如果您想動態添加新的TextView到您的layout。刪除第二個setContentView(),並在xml中將id指定給您的LinearLayout。然後在您的Java代碼中找到並說linearlayout.add(textview)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/lv" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal"> 
    <EditText android:id="@+id/edittext" 
     android:layout_weight="1" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:hint="@string/edit_message" /> 
    <Button android:id="@+id/send" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/button_send" /> 
</LinearLayout> 


Linearlayout lv=(Linearlayout) findViewById(R.id.lv); 
lv.add(textview); 
相關問題