我目前有一个带有标签和OptionsMenu的ActionBar。我的标签正确地打开每个片段,但我无法弄清楚如何使用onOptionsItemSelected打开片段。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_info) {
new ParentInfoSectionFragement();
return true;
} else if (id == R.id.action_history){
new NotificationHistorySectionFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
这就是我尝试过的,显然是错的。
任何帮助都将深表感谢。谢谢
activity_main.xml中
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.parentprojectmobile.MainActivity" />
fragment_history.xml
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.parentprojectmobile.MainActivity$PlaceholderFragment" >
<TextView
android:id="@+id/history_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_history" />
/RelativeLayout>
所有片段都只是原始片段的副本,只有用于学习目的的文本视图。
答案 0 :(得分:0)
使用活动的片段交易
示例:强>
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.layout_id, new ParentInfoSectionFragement(), null).commit();
其中R.id.layout_id
是您要放置片段的布局ID。
答案 1 :(得分:0)
你需要处理你的片段堆栈
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_info) {
new ParentInfoSectionFragement();
return true;
} else if (id == R.id.action_history){
new NotificationHistorySectionFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
notificationHistorySectionFragment = new NotificationHistorySectionFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, notificationHistorySectionFragment);
fragmentTransaction.addToBackStack(null);
//Commit Transaction
fragmentTransaction.commit();
}
return super.onOptionsItemSelected(item);
}
在此示例中,R.id.fragment_container
是布局中片段容器的ID。