Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing layout dynamically

I'm trying to create an activity to search with, and have 2 different layouts with different search criterion for each. I'd like to use a spinner to do this. Don't really have any code because what I tried already I deleted, but any help is appreciated.

like image 803
digipen79 Avatar asked Jun 16 '11 15:06

digipen79


Video Answer


1 Answers

You could switch the activity's entire content view to a new view or layout resource in your onItemSelected callback by using Activity.setContentView(), but I expect that isn't quite what you want as it would replace the spinner itself.

How about adding/replacing a child view into your activity's content view? This could be a view inflated from an XML resource, and they could share some view IDs to cut down on the code required (or you could delegate the behaviour to separate classes).

For example:

main.xml:

<LinearLayout ...> <!-- Root element -->
    <!-- Put your spinner etc here -->
    <FrameLayout android:layout_height="fill_parent"
                 android:layout_width="fill_parent"
                 android:id="@+id/search_criteria_area" />
</LinearLayout>

search1.xml:

<!-- Contents for first criteria -->
<LinearLayout ...>
    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="#ffff0000"
              android:id="@+id/search_content_text" />
</LinearLayout>

search2.xml:

<!-- Contents for second criteria -->
<LinearLayout ...>
    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="#ff00ff00"
              android:id="@+id/search_content_text" />
</LinearLayout>

Then in your activity, you could switch between them like so:

public class SearchActivity extends Activity {

    // Keep track of the child view with the search criteria.
    View searchView;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        ViewGroup searchViewHolder = (ViewGroup)findViewById(R.id.search_criteria_area);

        if (searchView != null) {
            searchViewHolder.removeView(searchView);
        }

        int searchViewResId;

        switch(position) {
        case 0:
            searchViewResId = R.layout.search1;
            break;
        case 1:
            searchViewResId = R.layout.search2;
            break;
        default:
            // Do something sensible
        }

        searchView = getLayoutInflater().inflate(searchViewResId, null);
        searchViewHolder.addView(searchView);

        TextView searchTextView = (TextView)searchView.findViewById(R.id.search_content_text);
        searchTextView.setText("Boosh!");
    }
}
like image 52
mrb Avatar answered Nov 28 '22 08:11

mrb