0

我想加载一个布局 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_bar.xml的布局文件。R.layout.activity_main是主要活动。是activity_main中容器R.id.layout_main的 id 。RelativeLayout

但我得到一个错误膨胀类

如何加载布局并将其添加到当前加载的布局中?

4

2 回答 2

1

I do not see an obvious problem with your code. As was mentioned in a comment, please post the log here.

May I suggest another approach? You could include the search bar (either in your main layout or using the include tag) and set it's visibility to GONE until you need to show it.

于 2013-05-05T20:16:55.367 回答
0

我做了一些研究,并结合了几个解决方案的提示。
首先,我使用LayoutInflater.from(Context)了而不是Context.LAYOUT_INFLATER_SERVICE(尽管这似乎不是问题)。第二,我用的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);
}
于 2013-05-06T09:48:20.867 回答