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.
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!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With