レイアウト 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
しかし、クラスを膨らませる際にエラーが発生しました。
レイアウトを読み込んで、現在読み込まれているレイアウトに追加するにはどうすればよいですか?