Frage

I have two xml files in the layout folder main.xml and hidden.xml. in my activity, the content view is set to main.xml using setcontentview. what I want to do is, to inflate the main.xml with hidden.xml when a certain button is pressed. To accomplish this, I wrote the below posted code.

But the problem is, while checking if the LinearLayout is null or not, it returns null as the toast displays a respective message.

My question is, what can cause a LinearLayout to be null since it is available in the hidden.xml ?

JavaCode:

public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.addBtn00:
            LinearLayout hiddenLinearLayout = (LinearLayout) findViewById(R.id.hiddenLayout00);
            if (hiddenLinearLayout == null) {
                Toast.makeText(getBaseContext(), "hidden layout is null", Toast.LENGTH_SHORT).show();
            }else {
                LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linearLayout01);
                View hiddenInfo = getLayoutInflater().inflate(R.id.hiddenLayout00, myLinearLayout,false);
                myLinearLayout.addView(hiddenInfo);
            }
            //TextView mTv = (TextView) findViewById(R.id.textView00);
            //mTv.setText("This is not the original Text");
            break;

        case R.id.removeBtn00:
            break;

        default:
            break;
        }

hidden.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:id="@+id/hiddenLayout00">
    <TextView 
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="This is a Text View" 
        android:layout_height="wrap_content"
        android:id="@+id/textView00" 
        android:layout_width="wrap_content" />
War es hilfreich?

Lösung

You are inflating in a wrong way, you should point to the layout at the first parameter, not to the id inside the layout. Replace this:

getLayoutInflater().inflate(R.id.hiddenLayout00, myLinearLayout,false);

with this:

getLayoutInflater().inflate(R.layout.hidden, myLinearLayout,false);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top