wit221 wit221 - 3 months ago 26
Android Question

How to make an XML element a blueprint to allow for re-usability?

My XML file is the following:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/border">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rants_list_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>


I then have a res/layout/sonich.xml file:

<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/sonich"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="32sp"
xmlns:android="http://schemas.android.com/apk/res/android"/>


My goal is to make the above TextView a reusable view, that is, reference it in the application multiple times to create text views of the properties specified in the above text view.

Hence, in the main activity, I do the following:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rants_list_linear_layout);
for (int i = 0; i< 100; i++) {
TextView txt = (TextView) findViewById(R.id.sonich);
linearLayout.addView(txt);
}


This, however, produces the following error:


java.lang.IllegalArgumentException: Cannot add a null child view to a
ViewGroup


This suggests that the findViewById() method returns a null reference. I do not understand why, since the text view is well defined in the xml file and the findViewById() method works well for the linear layout a few lines before that.

If I change the code to:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rants_list_linear_layout);
for (int i = 0; i< 100; i++) {
TextView txt = new TextView(this);
txt.setText("TextView");
txt.setTextSize(32);
linearLayout.addView(txt);
}


everything works fine. However, this is not what I want. I would like to outsource as much code to the xml files as possible. After all, the xml files exist to provide an organised way of specifying layouts, views etc. and their properties, whereas Java code is the one dealing with the app's functionality.

Could you please explain what this error stems from and how to create text views (or any views) programmatically, while referencing xml files to infer the views' properties?

Answer
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rants_list_linear_layout);
    LayoutInflater inflater = LayoutInflater.from(linearLayout.getContext());
    for (int i = 0; i< 100; i++) {
        View sonich = inflater.inflate(R.layout.sonich, linearLayout, false);
        TextView txt = (TextView) sonich.findViewById(R.id.sonich);
//      Now you don't need to do these since the XML takes care of it
//      txt.setText("TextView");
//      txt.setTextSize(32);
        linearLayout.addView(txt);
    }