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?
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:
You need to call
setContentView(R.layout.main);
before you callfindViewById
, as currentlylayoutContainer
will benull
.