开发者

Simple Android app fails without starting

开发者 https://www.devze.com 2023-03-09 20:55 出处:网络
Hello there people of stack overflow, I have just started developing with android and have run into a bit of a problem. I am trying to run a very simple app that has a single button, which when clicke

Hello there people of stack overflow, I have just started developing with android and have run into a bit of a problem. I am trying to run a very simple app that has a single button, which when clicked updates the text to the current time. However, the app does not even start up. I am following a book. "Beginning Android 2", and am just learning about XML layouts. T开发者_高级运维he same app worked without an XML layout, so it may be something to do with my xml.

Anyways, I'm running it on a droid 2, if that helps.

Heres the codes.

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());
    }
}

And the XML file

<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"
    />

Thanks in advance.


You should enclose the button inside a layout (linear, relative, etc):

<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>


Both answers are incorrect. The only line missing in that xml is the first one:

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

Of course you will need some kind of ViewGroup to make any meaningful UI, but setContentView can take any View as parameter


The problem is that your root layout must be a ViewGroup. Change the layout to something like this for example:

<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

精彩评论

暂无评论...
验证码 换一张
取 消