Using both XML and Coded views in Android

2019-08-12 12:59发布

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-08-12 13:26

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


    }
}
查看更多
倾城 Initia
3楼-- · 2019-08-12 13:36

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

    }
}
查看更多
登录 后发表回答