6

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

Ankesh kumar Jaisansaria
  • 1,563
  • 4
  • 26
  • 44

4 Answers4

5

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.

jaibatrik
  • 6,770
  • 9
  • 33
  • 62
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

jotik
  • 17,044
  • 13
  • 58
  • 123
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.

Community
  • 1
  • 1
Swapnil Bhoite
  • 392
  • 2
  • 12
  • I tried using setContentView but its not performing well – Ankesh kumar Jaisansaria Jun 28 '16 at 11:26
  • Yeah, that's why you should consider using `Fragment`s. 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](https://developer.android.com/reference/android/widget/SearchView.html#onActionViewExpanded()) in your Activity. – Swapnil Bhoite Jun 28 '16 at 11:32
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 :

Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39