使用切换按钮启动和停止菜单项

时间:2018-10-23 19:07:17

标签: java android android-studio togglebutton

这是我的MainActivity.java内部的代码: 我正在尝试使用切换按钮来切换要打开和关闭的菜单项。选中该菜单项会将背景设置为红色。未选择此项时,背景颜色为默认颜色。我是Java的新手,所以不确定在onCheckedChange下的if and else语句中应包含什么内容。任何建议都会有所帮助。 谢谢

import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button showFragBut = (Button)findViewById(R.id.button);
        showFragBut.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                String butText = showFragBut.getText().toString();

                FragmentManager fg = getSupportFragmentManager();
                FragmentTransaction ft = fg.beginTransaction();

                if (butText.equals("Add fragment")){
                    Frag1 frag = new Frag1();
                    ft.add(R.id.dyframe, frag, null);
                    ft.addToBackStack(null);
                    ft.commit();
                    showFragBut.setText("Remove fragment");
                } else {
                    getSupportFragmentManager().popBackStackImmediate();
                    showFragBut.setText("Add fragment");
                }
                MenuItem redMenuItem = (MenuItem)findViewById(R.id.menu_red);

            }
        });

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton4);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                } else {

                }
            }
        });


    }

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

    @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.
        ConstraintLayout mainLayout = (ConstraintLayout)findViewById(R.id.content1);
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch (id){
            case R.id.action_settings:
                if (item.isChecked())
                    item.setChecked(false);
                else
                    item.setChecked(true);
                Toast.makeText(getApplicationContext(), "Setting is clicked", Toast.LENGTH_LONG).show();
                return true;
            case R.id.menu_red:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                mainLayout.setBackgroundColor(Color.RED);
                return true;
            case R.id.menu_green:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                mainLayout.setBackgroundColor(Color.GREEN);
                return true;

        }

        return super.onOptionsItemSelected(item);
    }
}

XML:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/content1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".MainActivity"
        tools:showIn="@layout/activity_main">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="128dp"
            android:layout_marginTop="116dp"
            android:text="@string/button"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Add Fragment" />

        <FrameLayout
            android:id="@+id/dyframe"
            android:layout_width="185dp"
            android:layout_height="63dp"
            android:layout_marginStart="128dp"
            android:layout_marginTop="44dp"
            android:textAlignment="center"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button"/>

        <ToggleButton
            android:id="@+id/toggleButton4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="148dp"
            android:layout_marginBottom="110dp"
            android:text="@string/togglebutton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </android.support.constraint.ConstraintLayout>



<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.brettbanich.menuactivity.MainActivity">
    <group android:checkableBehavior="single" >
        <item
            android:id="@+id/menu_red"
            android:title="@string/red"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never" />
    </group>
</menu>

1 个答案:

答案 0 :(得分:1)

我认为这应该可行:

public void setColor(int color, boolean checked) {
    ConstraintLayout mainLayout = (ConstraintLayout)findViewById(R.id.content1);
    mainLayout.setBackgroundColor(color);
    redMenuItem.setChecked(checked);
}

并进行切换:

toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    setColor(Color.GREEN, true);
                } else {
                    setColor(Color.RED, false);
                }
            }
        });

我不确定颜色是否可以互换,这个想法是这样的。我假设您在setColor()中使用的onOptionsImetSelected()中的代码可以按预期工作。