代码之家  ›  专栏  ›  技术社区  ›  Ranhiru Jude Cooray

为什么这种基于XML布局的Android应用程序崩溃?

  •  0
  • Ranhiru Jude Cooray  · 技术社区  · 14 年前

    我对Android开发非常陌生。我正在尝试一个示例应用程序,它使用Java动态生成一个按钮,它运行良好。

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        btn=new Button(this);
        btn.setOnClickListener(this);
        updateTime();
        setContentView(btn);
        }
    

    这在我的模拟器中工作得很好。但是,当我尝试使用基于XML的布局时,我的应用程序在模拟器中崩溃。

    Main.XML 内容

    <?xml version="1.0" encoding="utf-8"?>
    <Button xmlns:android="com.testing"
        android:id="@+id/button"
        android:text=""
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    

    代码:

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.main);
    
            btn=(Button)findViewById(R.id.button);
            btn.setOnClickListener(this);
            updateTime();
    
        }   
    

    有人知道为什么这个简单的应用程序因为XML布局而崩溃吗? 提前太多了:)

    2 回复  |  直到 14 年前
        1
  •  1
  •   Cristian    14 年前

    尝试:

    <?xml version="1.0" encoding="utf-8"?>
    <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" />
    

    总之…如果您发布logcat输出,它将有所帮助。

        2
  •  1
  •   chakrit Dutchie432    14 年前

    这条线:

    xmlns:android="com.testing"
    

    应该指向Android的XML命名空间… 不是 您的包名称。

    xmlns:android="http://schemas.android.com/apk/res/android"
    

    但是,您可以重命名该单词 android 属性值保持不变。