-4

I have a Button in MainActivity want to add another XML on Button click event.

Please help me. It would be a very kind of you.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Gen. Kryan
  • 1
  • 1
  • 3

2 Answers2

2

Simply do one thing in your code define one Layout in your XML for any kind of View which you want to put in run time in XML, then make object of that Layout in your class and inflate another XML in this Layout object.

Try this code for inflate another XML in run time:

LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); 

// Put another XML name here with R.layout
    View view = inflater.inflate(R.layout.**XML**, null);

// Your Layout object   
    **layoutObject**.addView(view);
nivesh shastri
  • 430
  • 2
  • 13
1

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button2 = (Button)findViewById(R.id.button2);

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.layout);
        }
    });
}

@Override
public void onBackPressed()
{
  // Instead of setcontentview() i am restarting the activity.
    Intent i = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(i);
}
}

Layout.java

public class Layout extends Fragment{


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.layout, container, false);

    return v;
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
     android:id="@+id/RL">

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:id="@+id/button2" />


</RelativeLayout>

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fbb">

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    />
</RelativeLayout>

Note: Creating a fragment java class for other xml(in this case layout.xml) is necessary otherwise setContentView(R.layout.YourLayout) will not work and the app will crash immediately when opened.

Shweta Khera
  • 126
  • 5