Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close navigation drawer programmatically from another class

Tags:

java

android

I currently am using Fragments in my app. In my MainActivity I have a navigation drawer which is then subsequently populated by a Fragment, as well as the main area in the activity which is populated by another Fragment.

The clicking of an item in the navigation drawer is dealt with by my first fragment, only, the navigation drawer is in my MainActivity class. I can't seem to be able to close the navigation drawer (I can swipe it closed but I want it to auto close after an item has been clicked) from my fragment after an item has been clicked, is there any way to do this?

Heres my code:

MainActivity:

    public class MainActivity extends Activity {

LinearLayout mainContent;
LinearLayout background;
SharedPreferences prefs;
DataBase db;
SQLiteDatabase mDB;
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
TextView divider;
Typeface[] fonts = new Typeface[4];
Boolean isPortrait = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    String theme = prefs.getString("PREF_THEME", "holoWhite");
    if (theme.equals("holoWhite")) {
        setTheme(R.style.AppBaseTheme);
    } else {
        setTheme(R.style.AppBaseThemeDark);
    }

    if(getResources().getConfiguration().orientation == getResources().getConfiguration().ORIENTATION_LANDSCAPE){
        isPortrait = false;
    }

    setContentView(R.layout.activity_main);

    initialiseVariables();

    setTheme();
    loadInitialContentFragment();

    SQLiteDatabase dataB = db.getWritableDatabase();
    dataB.execSQL("DELETE FROM " + "StackTable");
    dataB.close();

    loadFrag(new LeftFragment(), null, R.id.mainLeftView);

    fonts[0] = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf");
    fonts[1] = Typeface.createFromAsset(getAssets(),
            "Roboto-LightItalic.ttf");
    fonts[2] = Typeface.createFromAsset(getAssets(), "Roboto-Medium.ttf");
    fonts[3] = Typeface.createFromAsset(getAssets(),
            "Roboto-MediumItalic.ttf");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

public void initialiseVariables() {
    db = new DataBase(this);
    background = (LinearLayout) findViewById(R.id.background);
    prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    mainContent = (LinearLayout) findViewById(R.id.mainContentView);
    if(!isPortrait){
        divider = (TextView)findViewById(R.id.mainLandDivider);
        divider.setBackgroundColor(new Colours().getARGBForBG(prefs.getString("PREF_COLOR", "blue"), prefs.getString("PREF_THEME", "holoWhite")));
    }
    if(isPortrait){
        mDrawerLayout = (DrawerLayout) findViewById(R.id.mainLeftDrawer);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                loadFrag(new LeftFragment(), null, R.id.mainLeftView);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView){
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }
}

public void loadInitialContentFragment() {
    loadFrag(new ContentFragment(), "none", R.id.mainContentView);

    SQLiteDatabase mDB = db.getWritableDatabase();
    ContentValues vals = new ContentValues();
    vals.put("LEVEL", "none");
    mDB.insert("StackTable", null, vals);

}

public void loadFrag(Fragment _fragment, String _parent, int id){
    Bundle bundle = new Bundle();
    bundle.putString("PARENT", _parent);
    _fragment.setArguments(bundle);
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager
            .beginTransaction();
    fragmentTransaction.replace(id, _fragment).commit();
}

public void setTheme() {
    if (prefs.getString("PREF_THEME", "holoWhite").equals("holoWhite")) {
        background.setBackgroundColor(Color.argb(255, 238, 238, 238));
    } else {
        background.setBackgroundColor(Color.argb(255, 20, 20, 20));
    }
}

@Override
public void onBackPressed() {
    String goTo = "";

    SharedPreferences prefs2 = getSharedPreferences(
            "uk.me.lewisdeane.jotterpro", Context.MODE_PRIVATE);

    SQLiteDatabase mDB = db.getReadableDatabase();
    Cursor C = mDB.query("NoteTable", new String[] { "PARENT", "NOTE",
            "TIME", "DATE", "REMINDER", "PASSWORD" }, "NOTE=?",
            new String[] { prefs2.getString(
                    "uk.me.lewisdeane.jotterpro.parent", null) }, null,
            null, null);

    if (C == null) {
        finish();
    } else if (!(C.moveToFirst()) || C.getCount() == 0) {
        finish();
    } else {
        C.moveToLast();
        do {
            goTo = C.getString(0);
        } while (C.moveToPrevious());
    }

    C.close();

    if (prefs2.getString("uk.me.lewisdeane.jotterpro.parent", null).equals(
            "none")) {
        finish();
    } else {
        loadFrag(new ContentFragment(), goTo, R.id.mainContentView);
    }
}

public void closeDrawer(){
    mDrawerLayout.closeDrawer(Gravity.LEFT);
}

public MainActivity(){

}

}

And my first fragment

          public class LeftFragment extends Fragment {

/*
 * 
 * THIS CLASS HANDLES THE UPCOMING NOTES FRAGMENT
 */

// Key items to the class
View rootView;
DataBase db;
SQLiteDatabase mDB;

// ArrayLists of the components of each note
ArrayList<String> mTitles = new ArrayList<String>();
ArrayList<String> mTimes = new ArrayList<String>();
ArrayList<String> mDates = new ArrayList<String>();
ArrayList<String> mReminders = new ArrayList<String>();
ArrayList<String> mPasswords = new ArrayList<String>();
ArrayList<String> mSubItems = new ArrayList<String>();
ArrayList<String> mSelected = new ArrayList<String>();

// Hash maps will hold the preferences
HashMap<String, String> strPrefs = new HashMap<String, String>();
HashMap<String, Boolean> boolPrefs = new HashMap<String, Boolean>();

// ListView to be used
ListView mListView;

// Load prefs
SharedPreferences prefs;

// Adapter...
CardAdapter mAdapter;

// Fonts
Typeface[] fonts = new Typeface[4];

// Stuff to do with storing dates and stuff
ArrayList<Long> intDates = new ArrayList<Long>();
Map<Long, String> mMap = new HashMap<Long, String>();

// Used in detecting password notes
int count = 0;
Boolean proceed = true;

// Boolean storing devices orientation
Boolean isPortrait = true;

// Title and edittext
EditText mHeader;

// TextView below the header
TextView mDivider;

// Background of whole fragment
LinearLayout mBackground;

public LeftFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.left_fragment, container, false);

    // Load all settings before doing anything
    loadPreferences();

    // Initialise the bulk of variables
    initialiseVariables();

    return rootView;
}

public void initialiseVariables() {
    // Define each item
    mListView = (ListView) rootView.findViewById(R.id.leftListView);
    mHeader = (EditText) rootView.findViewById(R.id.leftHeading);
    mDivider = (TextView) rootView.findViewById(R.id.leftDivider);
    mBackground = (LinearLayout) rootView.findViewById(R.id.leftBackground);

    // Set Adapter for listview
    mAdapter = new CardAdapter(getActivity(), R.layout.card_item, mTitles,
            mSubItems, mSelected, mTimes, mDates, mReminders, mPasswords);

    mListView.setAdapter(mAdapter);

    // Get Data
    getData();

    // Set up fonts
    fonts[0] = Typeface.createFromAsset(getActivity().getAssets(),
            "Roboto-Light.ttf");
    fonts[1] = Typeface.createFromAsset(getActivity().getAssets(),
            "Roboto-LightItalic.ttf");
    fonts[2] = Typeface.createFromAsset(getActivity().getAssets(),
            "Roboto-Medium.ttf");
    fonts[3] = Typeface.createFromAsset(getActivity().getAssets(),
            "Roboto-MediumItalic.ttf");

    // Apply settings to the header and listview
    if(strPrefs.get("PREF_THEME").equals("holoDark")){
        mHeader.setBackgroundColor(Color.BLACK);
        mHeader.setTextColor(new Colours().getARGBForBG(strPrefs.get("PREF_COLOR"), "PREF_THEME"));
        mHeader.setHintTextColor(Color.argb(255, 200, 200, 200));
        mDivider.setBackgroundColor(new Colours().getARGBForDivider(strPrefs.get("PREF_THEME")));
        mListView.setDivider(new ColorDrawable(new Colours().getARGBForDivider(strPrefs.get("PREF_THEME"))));
        mListView.setDividerHeight(10);
        mBackground.setBackgroundColor(new Colours().getARGBForDivider(strPrefs.get("PREF_THEME")));
    }

    // Set OnClickListeners and such...
    // Normal OnItemClick Listener...
    mListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            if (mSelected.size() == 0) {
                if (mPasswords.get(arg2).equals("")) {
                    loadFrag(new ContentFragment(), mTitles.get(arg2),
                            R.id.mainContentView);
                    MainActivity ma = new MainActivity();
                    ma.closeDrawer();
                } else {
                    openPassDialog(getPass(mTitles.get(arg2)),
                            mTitles.get(arg2));
                    new MainActivity().mDrawerLayout.closeDrawer(mListView);
                }
            } else {
                selectItem(arg0, arg1, arg2, arg3);
            }
        }
    });

    // OnItemLongClick Listener...
    mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            selectItem(arg0, arg1, arg2, arg3);
            return true;
        }
    });
            .......

I look forward to hearing your suggestions, thanks.

like image 967
nexodus Avatar asked Dec 28 '13 09:12

nexodus


2 Answers

Your DrawerLayout has a method called "closeDrawers()". I was having that problem and I used that in my "onChildClick" method. (My drawer had an ExpandableListView your might be a different callback like "onItemSelected" etc) It worked for me.

There's also closeDrawer(View view) and closeDrawer(int gravity). They might be helpful you too. So as long has you have a reference to the DrawerLayout you should be able to use one of these.

Documentation: https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#closeDrawers()

like image 83
RCB Avatar answered Nov 11 '22 04:11

RCB


On your MainActivity:

public void closeDrawer() {Drawer.closeDrawer(Gravity.LEFT);}

On your fragment class:

((MainActivity) getActivity()).closeDrawer();
like image 14
Alejandro Villarreal Avatar answered Nov 11 '22 03:11

Alejandro Villarreal