2011-05-31 55 views
0

你好,有堆棧溢出的人,我剛剛開始用android開發,並遇到了一些問題。我試圖運行一個非常簡單的應用程序,它有一個單一的按鈕,點擊時將文本更新爲當前時間。但是,該應用程序甚至不啓動。我正在閱讀一本書。 「開始Android 2」,並且剛剛瞭解XML佈局。相同的應用程序沒有XML佈局工作,所以它可能是與我的XML有關。簡單的Android應用程序無法啓動

無論如何,我在Droid 2上運行它,如果有幫助的話。

繼承人的代碼。

package apt.tutorial; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import java.util.Date; 

public class FirstApp extends Activity implements View.OnClickListener { 
    /** Called when the activity is first created. */ 
    Button btn; 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 

     setContentView(R.layout.main); 

     btn = (Button)findViewById(R.id.button); 
     btn.setOnClickListener(this); 
     updateTime(); 
    } 

    public void onClick(View view) { 
     updateTime(); 
    } 

    private void updateTime() { 
     btn.setText(new Date().toString()); 
    } 
} 

和XML文件

<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/button" 
    android:text="" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    /> 

在此先感謝。

+0

未來,當您遇到問題並希望獲得幫助時,請在遇到問題時提供'adb logcat *:D'的輸出。有了這些信息,它將減少必須提供答案的猜測量。 – 2011-05-31 02:05:06

+0

@Nick明白了,會做! – 2011-05-31 02:14:26

回答

2

你應該附上按鈕的佈局(線性的,相對的,等等)內:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > 
    <Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/button" 
    android:text="" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    /> 
</LinearLayout> 
+0

非常感謝,本書沒有提到這一點。我會盡快接受 – 2011-05-31 02:05:03

-1

的問題是,你的根佈局必須是一個ViewGroup中。將佈局更改爲如下所示:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <Button 
     android:id="@+id/button" 
     android:text="" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"/> 
</LinearLayout> 
0

這兩個答案都不正確。在XML唯一缺少的行是第一個:

<?xml version="1.0" encoding="utf-8"?> 

當然,你將需要某種形式的ViewGroup,使任何有意義的UI,但的setContentView可以採取任何查看參數