Android: Changing layout in same activity
Asked Answered
I

4

7

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

Indiaindiaman answered 28/6, 2016 at 11:14 Comment(0)
J
6

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.

Jodiejodo answered 28/6, 2016 at 11:27 Comment(0)
B
1

There are two ways to do it: one is make frame layout the parent tag for your layout and then create two layouts: one that you have already created and and one for search layout framed over it and make visibility for search layout GONE and when you click search make its visibility visible.

The second method is to create the new XML layout file for search layout and inflate it like this:

View v = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);

and elements of this layout will go like this:

Button button=(Button)v.findviewbyid(R.id.your_button_id);

Changing visibility of view will help in your case where you totally want to change the views

Bearish answered 28/6, 2016 at 11:22 Comment(0)
O
1

You can have a look at this question, but, this is not a good practice to follow and you should consider using Fragment or any other mechanism. By doing this you are cluttering your Activity's logic with search logic.

Overrate answered 28/6, 2016 at 11:24 Comment(2)
I tried using setContentView but its not performing wellIndiaindiaman
Yeah, that's why you should consider using Fragments. One simpler way would be to bring up the Search Fragment when SearchView in ActionBar is expanded and close it when SearchView is collapsed. You can listen to these callbacks in your Activity.Overrate
H
0

I think in your case, you should fragments to handle this situation.

Read this for more details on how to replace Fragments using FragmentManager.

Here's a nice example on how to change fragments in android :

Homoiousian answered 28/6, 2016 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.