对工具栏中的项目采取措施?

时间:2018-01-17 11:51:13

标签: android xml

我有ToolbarCustom有两个项目,可以点击一个项目来打开或关闭布局。我想知道如何使用相同的项目来打开和关闭布局?

这是我的代码,但未定义变量openLayout

 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();
        linearLayout = findViewById(R.id.show);
        boolean openLayout=true;
        if (id == R.id.action_categure) {
            if (openLayout) {
                linearLayout.setVisibility(View.VISIBLE);
                openLayout=false;
            } else  {
                linearLayout.setVisibility(View.GONE);
                openLayout =true;
            }

        }
        if (id==R.id.action_card){

          return true;
        }

        return super.onOptionsItemSelected(item);
    }

1 个答案:

答案 0 :(得分:0)

 boolean firstTimeClick = true;  //global variable
 boolean secondTimeClick = false;  //global variable

 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();
    linearLayout = findViewById(R.id.show);

    if (id == R.id.action_categure) {
        if (firstTimeClick) {
            firstTimeClick = false;
            secondTimeClick= true;
            linearLayout.setVisibility(View.GONE);

        } else if (secondTimeClick){
            firstTimeClick= true;
            secondTimeClick= false;
            linearLayout.setVisibility(View.VISIBLE);
       }
   }
    if (id==R.id.action_card){

      return true;
    }

    return super.onOptionsItemSelected(item);
}

这就是你想要达到的目标吗?希望我能帮到你。