在Android中使用XML和Coded视图

时间:2011-03-19 19:39:48

标签: java android xml layout mobile

我试图在Android操作系统中同时使用编码视图和xml视图。我希望xml布局保持基本布局和设置,而我将使用编码视图来创建更多动态部分。

这是我的设置,我没有收到任何编译错误但是应用程序在运行时崩溃了。 Java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TopImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layoutContainer = (LinearLayout) this.findViewById(R.id.layout_container);
        TextView tv = new TextView(this);
        layoutContainer.addView(tv);

        setContentView(R.layout.main);
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
        android:id="@+id/layout_container" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content">

    </LinearLayout>

</LinearLayout>

是不是可以同时使用两者?

2 个答案:

答案 0 :(得分:1)

在致电setContentView(R.layout.main);之前,您需要致电findViewById,因为目前layoutContainer将为null

public class TopImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        LinearLayout layoutContainer = (LinearLayout) this.findViewById(R.id.layout_container);
        TextView tv = new TextView(this);
        layoutContainer.addView(tv);

    }
}

答案 1 :(得分:0)

当你在主视图没有解决时,你试图获得一个视图,把这些行按相反的顺序排列:

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TopImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout layoutContainer = (LinearLayout) this.findViewById(R.id.layout_container);
        TextView tv = new TextView(this);
        layoutContainer.addView(tv);


    }
}