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

あなたのコードに明らかな問題は見当たりません。コメントで述べたように、ここにログを投稿してください。

別のアプローチを提案できますか?検索バーを (メイン レイアウトまたはインクルードタグを使用して)含め、表示する必要があるまで可視性をGONEに設定することができます。

于 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 に答える