Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Changing layout in same activity

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

like image 596
Ankesh kumar Jaisansaria Avatar asked Jun 28 '16 11:06

Ankesh kumar Jaisansaria


People also ask

Can one activity have multiple layouts?

Yes its possible. You can use as many layouts as possible for a single activity but obviously not simultaneously. You can use something like: if (Case_A) setContentView(R.

How do I change my activity layout?

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

Can you use a same xml layout for 2 different activities?

Yes, you can. Just call "setContentView" with the same xml and it will use the same layout. Change whatever you need to programmatically during runtime.

Is it possible to include one layout definition in another?

To efficiently reuse complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.


1 Answers

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.

like image 82
jaibatrik Avatar answered Sep 19 '22 00:09

jaibatrik