Android:根据所选片段更改菜单

时间:2016-01-04 18:18:39

标签: android android-fragments

我有不同的片段,但我想更改选项菜单。我只想要那个" Solicitudes"拥有它

The fragment that I want to have this option

This fragment shouldn't have it

我有一个带有main.xml的菜单文件夹,实际上我创建了另一个没有此设置选项的main2.xml,但我不知道如何更改

到目前为止,这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mTitle = mDrawerTitle = getTitle();

    fragment = new History();

oncreate:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

历史片段的代码:

public class History extends Fragment {
public static final String ARG_HISTORY = "arg_history";

public History() {
    // Empty constructor required for fragment subclasses
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.history, container, false);
    return rootView;
}

1 个答案:

答案 0 :(得分:3)

Fragment中,您需要说明Fragment控制菜单。

Fragment onCreate

setHasOptionsMenu(true);

现在,您可以在Fragment中实施以下内容,以隐藏您不想要的MenuItem

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.findItem(R.id.unwanted_item).setVisible(false);
    }

请确保在您希望Fragment进入的MenuItem中执行相反的操作。

如果您要添加MenuItem不属于Menu加载的Activity onCreateOptionsMenu,请执行Fragment @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_to_add_to_original, menu); super.onCreateOptionsMenu(menu, inflater); } 中的以下操作。

# models.py
class Book(models.Model):
    title = CharField(max_length=100)

class Loan(models.Model):
    book = ForeignKey(Book)

class Return(models.Model):
    loan = ForeignKey(Loan)