mercredi 1 février 2017

How to control menuItems visibility through checkboxes in Android Studio

I have created a navigation drawer activity in android studio. Now, I want to modify the code so that the visibility of the menu items can be altered through an onClick attribute.

The main app consists of several different checkboxes, when the user clicks any one of them, I want the app to display specific items in the menu and make the rest invisible.

I have declared several integers and initialized them as 0. Whenever, the user selects a checkbox, the integer values for the specific items that I want to be displayed are incremented.

Then, at last, if the value of any integer is still equal to zero, the menu item would be set as invisible else it would be visible.

The onCheckBoxSelected() method is used for this. When the user selects any one checkbox, the integer values are incremented.

Here is the source code for my MainActivity.java

package com.example.android.smartswitch;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

int scheduleSettings = 0;
int randomDelay = 0;
int temperatureSettings = 0;
int humiditySettings = 0;
int manualControl = 0;
int logging = 0;
int generalSettings = 0;

public void onCheckBoxSelected (View view)  {
    boolean checked = ((CheckBox)view).isChecked();


    switch (view.getId())  {
        //Using multiple switch statements to decide the visibility status of the item in the navigation drawer.

        case R.id.illuminatorBox1:
            if (checked) {
                scheduleSettings++;
                randomDelay++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.heaterBox2:
            if (checked) {
                temperatureSettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.timeHeaterBox3:
            if (checked) {
                scheduleSettings++;
                temperatureSettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.airConditionBox4:
            if (checked) {
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.timeAirConditionBox5:
            if (checked) {
                scheduleSettings++;
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.humidifierBox6:
            if (checked) {
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.timeHumidifierBox7:
            if (checked) {
                scheduleSettings++;
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.airDryerBox8:
            if (checked) {
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        case R.id.timeAirDryerBox9:
            if (checked) {
                scheduleSettings++;
                humiditySettings++;
                manualControl++;
                logging++;
                generalSettings++;
            }
            break;

        default:
            Toast.makeText(this, "Default Case Applied.... Find the *BUG*", Toast.LENGTH_LONG);
            break;
    }
}

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

    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.addDrawerListener(toggle);
    toggle.syncState();

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

    Menu nav_menu = navigationView.getMenu();       //To hide items from the menu if conditions aren't fulfilled.

    if (scheduleSettings == 0)
        nav_menu.findItem(R.id.scheduleSettingsSideBar).setVisible(true);

    else if (randomDelay == 0)
        nav_menu.findItem(R.id.randomDelaySideBar).setVisible(false);

    else if (temperatureSettings == 0)
        nav_menu.findItem(R.id.tempSettingsSideBar).setVisible(false);

    else if (humiditySettings == 0)
        nav_menu.findItem(R.id.humiditySettingsSideBar).setVisible(false);

    else if (manualControl == 0)
        nav_menu.findItem(R.id.manualSettingsSideBar).setVisible(false);

    else if (logging == 0)
        nav_menu.findItem(R.id.loggingSideBar).setVisible(false);

    else if (generalSettings == 0)
        nav_menu.findItem(R.id.generalSettingsSideBar).setVisible(false);

}

int controllerButton = 1;       //Depending on this value, the main screen text will change.

public void onButtonClick(View view) {
    switch (view.getId()) {
        case R.id.settingsButton:
            Intent intent = new Intent(this, logging_screen.class);
            startActivity(intent);
            break;

        case R.id.controllerButton:
            if (controllerButton == 1) {
                Button button1 = (Button) findViewById(R.id.controllerButton);
                button1.setBackgroundColor(Color.GREEN);        //Changing the background of the controllerButton.
                button1.setText(getString(R.string.controller_off_text));
                Button headerButton = (Button) findViewById(R.id.headerText);
                headerButton.setBackgroundColor(Color.RED);
                headerButton.setTextColor(Color.BLACK);
                headerButton.setText(getString(R.string.banner_off_text));

                controllerButton = 0;         //Setting the button int to zero for next change.
            } else if (controllerButton == 0) {
                Button button1 = (Button) findViewById(R.id.controllerButton);
                button1.setBackgroundColor(Color.parseColor("#33b5e5"));        //Changing the background of the controllerButton.
                button1.setText(getString(R.string.controller_on_text));
                Button headerButton = (Button) findViewById(R.id.headerText);
                headerButton.setBackgroundColor(Color.parseColor("#000000"));
                headerButton.setTextColor(Color.WHITE);
                headerButton.setText(getString(R.string.banner_on_text));

                controllerButton = 1;         //Setting the button int to one for next change. An altering loop.
            }
            break;
    }
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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;
}

@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.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.scheduleSettingsSideBar) {
        //Intent to send the user to scheduleSettings Screen.
        Intent intent = new Intent(this, schedule_settings.class);
        startActivity(intent);


    } else if (id == R.id.manualSettingsSideBar) {
        Intent intent = new Intent(this, manual_control.class);
        startActivity(intent);

    } else if (id == R.id.tempSettingsSideBar) {
        //Intent to send the user to tempSettings Screen.
        Intent intent = new Intent(this, temp_screen.class);
        startActivity(intent);
    } else if (id == R.id.randomDelaySideBar) {
        Intent intent = new Intent(this, random_delay.class);
        startActivity(intent);

    } else if (id == R.id.humiditySettingsSideBar) {
        Intent intent = new Intent(this, humidity_settings.class);
        startActivity(intent);

    } else if (id == R.id.loggingSideBar) {
        //Intent to send the user to loggingSidebar.
        Intent intent = new Intent(this, logging_screen.class);
        startActivity(intent);

    } else if (id == R.id.generalSettingsSideBar) {
        Intent intent = new Intent(this, general_settings.class);
        startActivity(intent);

    } else if (id == R.id.playSliderAgain) {
        //We normally won't show the welcome slider again in real app
        // but this is for testing
        slidingScreenLauncher prefManager = new slidingScreenLauncher(getApplicationContext());
        // make first time launch TRUE
        prefManager.setFirstTimeLaunch(true);
        startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
        finish();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}

But, this program has a bug, the menu items are being displayed by default, I don't know why. The app runs normally and does everything as expected except this.

Please help as I won't be able to improve my app if this issue persists. Any other approach that would have the same output (setting menu items invisible) is also welcomed.....




Aucun commentaire:

Enregistrer un commentaire