Android: Changing layout in same activity

Ankesh kumar Jaisansaria picture Ankesh kumar Jaisansaria · Jun 28, 2016 · Viewed 15.1k times · Source

In my application's main layout I have a button of Search task. Now when user clicks that button I want to change the layout xml file to search_layout.xml. I don't want to create a new activity for Search task and want to use my activity_main.java class for its coding. So how do I inflate search_layout from existing activity_main.xml .

My activity_main layout is Coordinating layout with Collapsing toolbar and Recycler view.

In my search_layout.xml I have a Simple relative layout.

So how to deal with this ? I searched for this but everywhere I get how to inflate view adding to an existing view. But in my case I want to totally change view.

Thanks

Answer

jaibatrik picture jaibatrik · Jun 28, 2016

You can simply call setContentView(R.layout.your_search_layout) in the click listener of your button.

Example -

yourButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        setContentView(R.layout.your_search_layout);
    }
});

However, it is always good practice to make your code modular, hence you should consider using Fragments to achieve this.