我目前正在我的应用中使用Fragments。在我的MainActivity中,我有一个导航抽屉,然后由Fragment填充,以及活动中由另一个Fragment填充的主要区域。
导航抽屉中项目的点击由我的第一个片段处理,导航抽屉在我的MainActivity类中。在单击某个项目后,我似乎无法关闭导航抽屉(我可以将其关闭但我希望它在点击项目后自动关闭)从我的片段关闭,是否有任何方法可以执行此操作?
继承我的代码:
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(){
}
}
我的第一个片段
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;
}
});
.......
我期待听到您的建议,谢谢。
答案 0 :(得分:36)
你的DrawerLayout有一个名为&#34; closeDrawers()&#34;的方法。 我遇到了这个问题,我在我的&#34; onChildClick&#34;方法。 (我的抽屉有一个ExpandableListView你可能是一个不同的回调,如&#34; onItemSelected&#34;等) 它对我有用。
还有closeDrawer(View view)和closeDrawer(int gravity)。他们也可能对你有所帮助。因此,只要你有一个DrawerLayout的引用,你应该可以使用其中一个。
文档:https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#closeDrawers()
答案 1 :(得分:12)
在您的MainActivity上:
public void closeDrawer() {Drawer.closeDrawer(Gravity.LEFT);}
在你的片段类上:
((MainActivity) getActivity()).closeDrawer();
答案 2 :(得分:1)
如果您在DrawerLayout中使用Fragment作为NavigationView,则必须在closeDrawer / openDrawer方法中将片段视图作为参数发送:
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mFragment.getView());
if (mDrawerLayout.isDrawerOpen(mFragment.getView())) {
mDrawerLayout.closeDrawer(mFragment.getView());
} else {
mDrawerLayout.openDrawer(mFragment.getView());
}
我希望它可以帮到你。