仅对特定操作栏菜单进行通知

时间:2017-06-05 04:33:46

标签: android android-fragments android-actionbar

我的主要活动中定义了一个操作栏菜单。现在,我在该活动中使用的一个片段有自己的操作栏菜单,但是当我点击菜单选项时,我同时获得片段和活动的菜单项。如何确保只显示该片段的菜单项?

我对该片段的java代码是:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/edit_profile"
    android:orderInCategory="100"
    android:title="Edit"
    app:showAsAction="never" />

</menu>

菜单的xml文件是:

10,

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。我在这里发帖,所以如果其他人面临同样的问题,他们可以从中受益:

我创建了一个静态菜单对象,并在该对象中存储了活动的操作栏菜单。然后我从我的片段中调出该对象并将其清除,从而清除活动菜单并留下片段的菜单

这是片段

的更新java代码
public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    HomePage.menu_home.clear();

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}