В настоящее время я использую фрагменты в своем приложении. В моей MainActivity у меня есть ящик навигации, который затем заполняется фрагментом, а также основной областью в активности, которая заполняется другим фрагментом.
Щелчок элемента в ящике навигации обрабатывается только моим первым фрагментом, только ящик навигации находится в моем классе 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;
}
});
.......
Я с нетерпением жду ваших предложений, спасибо.