Using both XML and Coded views in Android

天涯浪子 提交于 2020-02-04 23:06:13

问题


I am trying to use both a coded views and an xml views at the same time in the Android OS. I want the xml layout to hold the basic layout and setup, while I will use coded views to create more dynamic parts.

Here's my setup, I receive no compiling errors but the app crashes when ran. The 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);
    }
}

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

Is it not possible to use both?


回答1:


You need to call setContentView(R.layout.main); before you call findViewById, as currently layoutContainer will be 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);

    }
}



回答2:


well you are traying to get a view while the main view isn't setted at that time, put the lines in the inverse order:

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


    }
}


来源:https://stackoverflow.com/questions/5364433/using-both-xml-and-coded-views-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!