动态更改布局

5

我想创建一个带有两种不同搜索条件的活动,并为每种条件使用不同的布局。我想使用下拉菜单来实现这一点。因为我已经删除了之前尝试过的代码,所以目前没有任何代码可供参考。但是,如果您能提供帮助,我将不胜感激。


1
我不明白你真正想要做什么? - dymmeh
是的,我在写这个的时候可能有些走神了,但我正在使用的网络服务搜索有两种不同类型的搜索,每种搜索都有不同的搜索条件。我想要两种不同的布局,每种搜索一种。我希望有一个下拉菜单可以在两种搜索之间切换。 - digipen79
1个回答

9
您可以在onItemSelected回调中使用Activity.setContentView()将活动的整个内容视图切换为新的视图或布局资源,但我认为这并不是您想要的,因为它会替换掉下拉菜单本身。
那么,将子视图添加/替换到活动的内容视图中如何?这可以是从XML资源膨胀的视图,并且它们可以共享一些视图ID以减少所需的代码(或者您可以将行为委托给单独的类)。
例如: 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>

然后在您的活动中,您可以像这样在它们之间切换:

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!");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接