프레그먼트에서 다른 레이아웃 뷰 호출
조회수 2605회
activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.app.FragmentTabHost
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tabhost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabs"></TabWidget>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="49dp"
android:id="@+id/tabcontent"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/realtabcontent"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
여기에 선언된 툴바를 fagment에서 사용하고 싶습니다.
fragment1.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInistanceState) {
// Inflate the layout for this fragment0
View view = inflater.inflate(R.layout.fragment1, container, false);
View v = inflater.inflate(R.layout.activity_main, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
...
}
이 부분에서 엑티비티 메인에 선언된 툴바를 찾아오는 코드가 맞나요?? 이렇게 사용하니 적용이 안되네요 ..
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
...
}
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
activity_main은 액티비티가 생성될 때 인플레이트 되기 때문에 작성하신 코드처럼 프래그먼트에서 인플레이트를 하는 것은 의미가 없습니다. 다음과 같이 코드를 수정해보세요.
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, container, false); Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); setHasOptionsMenu(true); ... return view; }
setSupportActionBar(toolbar)는 액티비티에서 호출하는 것이 더 나을 것 같습니다.
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ... }
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력