如何在Android中加载一个版面并将其添加到另一个版面?

如何在Android中加载一个版面并将其添加到另一个版面?,android,android-layout,android-search,Android,Android Layout,Android Search,我想加载一个布局XML文件,并将布局添加到当前内容视图中 所以,如果我在这里得到这个布局: 如果我点击硬件搜索按钮,那么我想在屏幕顶部显示一个搜索栏,如下所示: 基于此,我尝试了以下方法: MainActivity.java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acti

我想加载一个布局XML文件,并将布局添加到当前内容视图中

所以,如果我在这里得到这个布局:

如果我点击硬件搜索按钮,那么我想在屏幕顶部显示一个搜索栏,如下所示:

基于此,我尝试了以下方法:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.search_bar, null);

    ViewGroup layout = (ViewGroup) findViewById(R.id.layout_main);
    layout.addView(v);
}
搜索栏是一个名为search\u bar.xml的布局文件<代码>右布局。活动\u main是主要活动
R.id.layout\u main
RelativeLayout
的id,它是活动\u main中的容器

但我在给班级充气时出错了


如何加载版面并将其添加到当前加载的版面?

我认为您的代码没有明显的问题。正如在评论中提到的,请在这里发布日志


我可以建议另一种方法吗?您可以包括搜索栏(在主布局中或使用标记),并将其可见性设置为,直到需要显示为止。

我做了一些研究,并将几个提示组合到解决方案中。
首先,我使用了
LayoutInflater.from(Context)
而不是
Context.LAYOUT\u flater\u服务
(尽管这似乎不是问题)。其次,我使用了
onSearchRequest()
方法

结果是:

/**
 * Whether the search bar is visible or not.
 */
private boolean searchState = false;

/**
 * The View loaded from the search_bar.xml layout.
 */
private View searchView;

/**
 * This method is overridden from the Activity class, enabling you to define events when the hardware search button is pressed.
 *
 * @return Returns true if search launched, and false if activity blocks it.
 */
public boolean onSearchRequested() {
    // Toggle the search state.
    this.searchState = !this.searchState;
    // Find the main layout
    ViewGroup viewGroup = (ViewGroup) findViewById(R.id.layout_main);
    // If the search button is pressed and the state has been toggled on:
    if (this.searchState) {
        LayoutInflater factory = LayoutInflater.from(this.activity);
        // Load the search_bar.xml layout file and save it to a class attribute for later use.
        this.searchView = factory.inflate(R.layout.search_bar, null);
        // Add the search_bar to the main layout (on position 0, so it will be at the top of the screen if the viewGroup is a vertically oriented LinearLayout).
        viewGroup.addView(this.searchView, 0);
    }
    // Else, if the search state is false, we assume that it was on and the search_bar was loaded. Now we remove the search_bar from the main view.
    else {
        viewGroup.removeView(this.searchView);
    }
    return false;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

什么错误?你能给我们提供航海日志吗?