动态更改布局

dig*_*n79 5 android android-layout

我正在尝试创建一个要搜索的活动,并且有两个不同的布局,每个布局都有不同的搜索条件.我想用旋转器来做这件事.不要真的有任何代码,因为我已经尝试删除了,但任何帮助表示赞赏.

mrb*_*mrb 8

您可以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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)