I want to build an android application with a Fragment which contains a List of Option and if I click on one of this option, I can see, another fragment with other option.
So I build this:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity"
tools:ignore="MergeRootFrame" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="480dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" >
<ListView
android:id="#+id/left_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:background="#6dc659"
android:foreground="#color/white">
</ListView>
<fragment
android:id="#+id/navigation_drawer"
android:name="it.eresult.decipher.fragment.NavigationDrawerFragment"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
This is the MainActivity.java
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks{
private DrawerLayout drawer;
private ListView leftList;
private String[] leftListStrings;
private String[] rightListStrings;
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
leftList = (ListView) findViewById(R.id.left_list);
leftListStrings = getResources().getStringArray(R.array.principal_menu);
leftList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,leftListStrings));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
leftList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
arg1.setBackgroundColor(getResources().getColor(R.color.selected_menu_option));
if(arg2 == 0){
}
}
});
drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerSlide(View arg0, float arg1) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerOpened(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerClosed(View arg0) {
// TODO Auto-generated method stub
//rightList.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
//TODO
}
class MayAdapter extends ArrayAdapter<String>{
List<String> myList = null;
public MayAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
myList = objects;
}
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("omnia");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
This is NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
Toolbar toolBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
}
// Select the default item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// the fragment has menu items to contribute
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.social_history),
getString(R.string.encounter),
getString(R.string.problems),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
null,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
};
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
With this code, if I try to run my application, I can see the complete menu like this
Instead, I want to see only the left menu, and if I click on one items, see the right menu
Related
In my project I have a main activity with 3 fragments that are displayed via a ViewPager in a TabLayout on launch. In one of my fragments I have a RecyclerView and a FAB that, when clicked, launches an alert dialog that captures user input to be displayed in the RV in the fragment. Upon clicking ADD in the dialog, nothing appears in the RV but when I click the FAB and try again, it appears in the RV. So what I am saying, I have to input info in the FAB twice before it displays in my RV in my fragment. So I was wondering if someone could help me understand why this is happening. It seems like my RV in my frag is not being created right away, but all in all my app is not crashing so I have no log to post. I've research but to no avail. I am self taught so any help would be appreciated.
Fragment
public class SubjectsFrag extends DialogFragment implements CardAdapter.ClickListener,
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public CardAdapter cardAdapter;
public SubjectsModel model = null;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper dbHelper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
cardAdapter = new CardAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cardAdapter);
return view;
}
#Override
public void itemClicked(View view, int position) {
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel(sTitle, sTeacher);
model.setmTitle(title);
model.setmTeacher(teacher);
subMod.add(model);
cardAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Dialog Fragment
public class SubjectsEditor extends DialogFragment
{
Context context;
private OnAddSubjectListener listener;
#BindView(R.id.main_root)
ViewGroup root;
public interface OnAddSubjectListener
{
void OnAddSubjectSubmit(String title, String teacher);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try{
listener = (OnAddSubjectListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement onAddSubjectListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.editor_subjects, container, false);
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate(R.layout.editor_subjects, root);
final EditText mTitle = view.findViewById(R.id.edit_subject);
final EditText mTeacher = view.findViewById(R.id.edit_subject_teacher);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Add Subject")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sTitle = mTitle.getText().toString();
final String sTeacher = mTeacher.getText().toString();
listener.OnAddSubjectSubmit(sTitle, sTeacher);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Recycler Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>
{
public ArrayList<SubjectsModel> subMod;
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
public CardAdapter(Context context, ArrayList<SubjectsModel> items)
{
this.context = context;
this.subMod = items;
}
#NonNull
#Override
public CardAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
return new CardViewHolder(LayoutInflater.from(context).inflate(R.layout.subjects_item_list,
parent, false));
}
#Override
public void onBindViewHolder(final CardAdapter.CardViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
}
public class CardViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public CardViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
clickListener.itemClicked(view, getAdapterPosition());
Toast.makeText(context, R.string.hello_blank_fragment, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public int getItemCount()
{
return subMod.size();
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
CardAdapter.clickListener = clicked;
}
public interface ClickListener
{
public void itemClicked(View view, int position);
}
}
Fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
Main Activity
public class OverviewActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
CharSequence tabTitles[] = {"SUBJECTS", "TASKS", "CALENDER"};
int numOfTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_nav);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), tabTitles, numOfTabs);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
setupDrawerContent(mNavigationView);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed()
{
//DrawerLayout drawer = 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_nav, 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);
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.nav_grades:
Intent gradesIntent = new Intent(this, GradesActivity.class);
startActivity(gradesIntent);
break;
case R.id.nav_notes:
Intent notesIntent = new Intent(this, NotesActivity.class);
startActivity(notesIntent);
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawer.closeDrawer(GravityCompat.START);
}
}
Using notifyDataSetChanged() should do the trick. Check this answer
Giving it a once-over, nothing jumped out. You can use either the debugger or Log.d(String, String) calls to challenge your assumptions about what’s being called when. I’d take a closer look at when you call your adapter’s notifyDataSetChanged() and then at the getItemCount and bind or createViewHolder calls inside the adapter itself.
Hello everyone I'm developing an app that uses old navigation drawer approach. When I update 'com.android.support:appcompat-v7:23.1.1' to 'com.android.support:appcompat-v7:23.4.0' my navigation drawer not opening.
I debugged code and look for deprecated items but could not find any error code or message. Everything works perfectly but navigation drawer is not opening. Here is my code. Thanks in advance.
MainActivity.class
public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {
TapuUtils tapuUtils = new TapuUtils();
String userMail, userPassword;
SharedPreferences.Editor editor;
SharedPreferences preferences;
Tracker mTracker;
Bundle bundle;
String tapuAuth = "false";
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
userMail = bundle.getString("personname");
userPassword = bundle.getString("personpassword");
tapuAuth = bundle.getString("tapu");
}
TapuCredentials.setUserMail(userMail);
TapuCredentials.setUserPassword(userPassword);
TapuCredentials.setTapuAuth(tapuAuth);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit_alert))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
LoginActivity.fa.finish();
}
})
.setNegativeButton(getString(R.string.no), null)
.show();
}
#Override
public void onStart() {
super.onStart();
Countly.sharedInstance().onStart();
}
#Override
public void onStop() {
super.onStop();
Countly.sharedInstance().onStop();
}
#Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(getResources().getString(R.string.main_screen));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
Here is my NavigationDrawer.class
public class NavigationDrawerFragment extends Fragment {
private static NavigationDrawerAdapter myAdapter;
public static ArrayList<ListItem> myItems = new ArrayList<>();
public static UserCredentials mUserCredentials = new UserCredentials();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private DynamicListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
static LegendFragment frLegend = new LegendFragment();
Button mEditLayers, mShowLegend;
String personName,userType,tapucontrol;
TextView mLayersText;
static FragmentManager fragmentManager;
Bundle extras;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
if (savedInstanceState == null) {
extras = getActivity().getIntent().getExtras();
if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
}
personName = extras.getString("personname");
userType = extras.getString("usertype");
tapucontrol = extras.getString("tapu");
}
mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
mDrawerListView.setAdapter(myAdapter);
fragmentManager = getFragmentManager();
mDrawerListView.setCheeseList(myItems);
mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditLayers = (Button) rootView.findViewById(R.id.button);
mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
mEditLayers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditLayers.getText().equals("Düzenle")) {
myAdapter.setEditMode(true);
mEditLayers.setText(getActivity().getString(R.string.ok));
} else {
myAdapter.setEditMode(false);
mEditLayers.setText(getActivity().getString(R.string.editlayers));
}
}
});
return rootView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (frLegend.isAdded()) {
ft.remove(frLegend);
ft.commitAllowingStateLoss();
mEditLayers.setVisibility(View.VISIBLE);
mLayersText.setText("Katmanlar");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
Intent s = new Intent(getActivity(), SearchMainActivity.class);
s.putExtra("username", mUserCredentials.getUserName());
s.putExtra("password", mUserCredentials.getPassword());
s.putExtra("tapu",tapucontrol);
startActivity(s);
break;
case R.id.action_basemaps:
Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
startActivity(cb);
break;
case R.id.action_addlayer:
if (isNetworkAvailable(getActivity())) {
Intent al = new Intent(getActivity(), AddLayerActivity.class);
al.putExtra("usertype", userType);
startActivity(al);
} else {
Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_about:
Intent au = new Intent(getActivity(), AboutActivity.class);
au.putExtras(extras);
startActivity(au);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class ListItem {
String textdata;
Integer progress;
public ListItem(String textdata, int progress) {
this.textdata = textdata;
this.progress = progress;
}
public boolean equals(Object o) {
ListItem ndListItemObject = (ListItem) o;
return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
}
}
public void addLayersection(String name, int progress) {
ListItem listItem = new ListItem(name, progress);
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.contains(listItem)) {
myItems.remove(listItem);
} else {
myItems.add(0, listItem);
}
}
}
myAdapter.notifyDataSetChanged();
}
public int getListSizee() {
return myItems.size();
}
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
The Drawer is locked.
Change
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
to
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Here is the late solution that I find with myself. drawerOpenCloseControl is boolean flag. I am controlling true or false. And then open and close manually.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(drawerOpenCloseControl){
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
drawerOpenCloseControl = false;
}
else{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerOpenCloseControl = true;
}
break;
}
return super.onOptionsItemSelected(item);
}
As part of an application, I have set up a menuDrawer . I want to add a sub-menu , but I do not know where to start. Here is my code :
MainActivity :
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
case 2:
objFragment = new menu3_Fragment();
break;
case 3:
objFragment = new menu4_Fragment();
break;
case 4:
objFragment = new menu5_Fragment();
break;
case 5:
objFragment = new menu6_Fragment();
break;
case 6:
objFragment = new menu8_Fragment();
break;
case 7:
objFragment = new menu9_Fragment();
break;
case 8:
objFragment = new menu10_Fragment();
break;
case 9:
objFragment = new menu7_Fragment();
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
}
NavigationDrawerFragement
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("1", getResources().getDrawable(R.drawable.1)));
items.add(new NavigationItem("2", getResources().getDrawable(R.drawable.2)));
items.add(new NavigationItem("3", getResources().getDrawable(R.drawable.3)));
items.add(new NavigationItem("4", getResources().getDrawable(R.drawable.4)));
items.add(new NavigationItem("5", getResources().getDrawable(R.drawable.5)));
items.add(new NavigationItem("6", getResources().getDrawable(R.drawable.6)));
items.add(new NavigationItem("7", getResources().getDrawable(R.drawable.7)));
items.add(new NavigationItem("8", getResources().getDrawable(R.drawable.8)));
items.add(new NavigationItem("9", getResources().getDrawable(R.drawable.9)));
items.add(new NavigationItem("10", getResources().getDrawable(R.drawable.10)));
return items;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
* #param toolbar The Toolbar of the activity.
*/
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
/*public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}*/
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}}
activity_main :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent">
<include android:id="#+id/toolbar_actionbar" layout="#layout/toolbar_default"
android:layout_width="match_parent" android:layout_height="wrap_content" />
<android.support.v4.widget.DrawerLayout android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:clickable="true" android:layout_height="match_parent" />
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment android:id="#+id/fragment_drawer"
android:name="gisclace.foobar.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent" android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Thx in advance
I was having some problem when trying to make my navigation drawer in Android accessible from all Activity. I have a NavigationDrawer.java:
public class NavigationDrawer extends Activity {
static Context context;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mEventSelection;
private String[] mProfileSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mEventSelection = getResources().getStringArray(R.array.event_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
listParent.add(new SampleTO(getString(R.string.eventDrawer),
R.drawable.event));
listDataChild.put(getString(R.string.eventDrawer),
Arrays.asList(mEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
// Navigation drawer with sub menu goes here
public void selectItem(int groupPosition, int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
if (groupPosition == 0) {
switch (selectedPosition) {
case 0:
break;
case 1:
break;
}
// Navigation item for event
else if (groupPosition == 3) {
switch (selectedPosition) {
case 0:
Intent eventMain = new Intent(context, EventMain.class);
context.startActivity(eventMain);
break;
case 1:
Toast.makeText(NavigationDrawer.this, "Analyze Event",
Toast.LENGTH_LONG).show();
break;
}
}
setTitle(mEventSelection[selectedPosition]);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter
.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.amenityDrawer))) {
Toast.makeText(NavigationDrawer.this, "Amenity",
Toast.LENGTH_LONG).show();
setTitle(parentTitle);
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(groupPosition, childPosition);
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(navDrawerView);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And then I navigate to my second class which is EventMain.java when the sub item from navigation drawer is selected:
public class EventMain extends NavigationDrawer {
public static MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
LocationManager locationManager;
public static GraphicsLayer graphicsLayer = null;
public static Callout callout;
private int mYear, mMonth, mDay, mHour, mMinute;
private Calendar c;
static final int DATE_DIALOG_ID = 1;
static final int TIME_DIALOG_ID = 2;
private LinearLayout legendDiv, llNewsFeed, llSearch;
private ListView listview;
private Button btnNewsFeed, btnSearchAddr, btnLegends;
private EditText searchAddrET;
private ImageView ivEventGuide;
public static LinearLayout directionDiv;
public static TextView tvDirection, tvDirectionTitle, tvSearchTitle;
static EventController eventCtrl = new EventController();
static Event eventModel = new Event();
private ListAdapter mAdapter;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
ArcGISRuntime.setClientId("UkIVSWzquykoxCMG");
super.onCreate(savedInstanceState);
setContentView(R.layout.event_main);
context = this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.event_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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
It did shows the navigation drawer icon at the EventMain.java. However, when I try to expand it, it does not work. Any ideas?
Thanks in advance.
The xml layout of my EventMain:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.esri.android.map.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
initExtent="21801.3, 25801.0, 33218.7, 44830.0" >
</com.esri.android.map.MapView>
//Other linear and relative layouts
</FrameLayout>
</LinearLayout>
In EventMain's onCreate() method, setContentView() is being called after the call to the super.onCreate() method. This is causing the DrawerLayout set in the base class, NavigationDrawer, to be replaced, effectively removing the Drawer. To prevent this, we ensure the DrawerLayout has the standard container FrameLayout for main content, and inflate EventMain's layout into that.
The base Activity's layout, main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
...
</android.support.v4.widget.DrawerLayout>
And in the Activity subclass, EventMain:
#Override
public void onCreate(Bundle savedInstanceState) {
...
super.onCreate(savedInstanceState);
ViewGroup content = (ViewGroup) findViewById(R.id.event_frame);
getLayoutInflater().inflate(R.layout.event_main, content, true);
...
}
I am learning about Fragments in Android and I have a problem with Logcat.
I have 2 Activities and 2 Fragments, with their Layouts:
PlayerActivity - PlayerFragment / activity_player - fragment_player
LibraryActivity - LibraryFragment / activity_library - fragment_library
I have a button in PlayerFragment to LibraryActivity, where I inflate LibraryFragment. The problem is when I am in LibraryFragment Logcat doesn't show anything.
This is the Intent that I use to call to LibraryActivity (This button is in PlayerFragment in the method onActivityCreated)
final Button to_library = (Button) getView().findViewById(R.id.library);
to_library.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(getActivity(), LibraryActivity.class);
startActivity(newIntent);
}
});
LibraryActivity:
public class LibraryActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.library, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_library,
container, false);
return rootView;
}
}
}
LibraryFragment
public class LibraryFragment extends Fragment {
private final String LOG_TAG = "test";
public LibraryFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v(LOG_TAG, "onAttach");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(LOG_TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_library, container,
false);
Log.v(LOG_TAG, "onCreateViewLibraryFragment");
/*
* Aquí podemos seleccionar las Views contenidas en el Layout para
* trabajar con ellas, por ejemplo con: TipoView miView = (TipoView)
* rootView.findViewById(R.id.miViewXML);
*/
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v(LOG_TAG, "onActivityCreatedLibraryFragment");
}
#Override
public void onStart() {
super.onStart();
Log.v(LOG_TAG, "onStart");
}
#Override
public void onResume() {
super.onResume();
Log.v(LOG_TAG, "onResume");
}
#Override
public void onPause() {
super.onPause();
Log.v(LOG_TAG, "onPause");
}
#Override
public void onStop() {
super.onStop();
Log.v(LOG_TAG, "onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.v(LOG_TAG, "onDestroyView");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(LOG_TAG, "onDestroy");
}
#Override
public void onDetach() {
super.onDetach();
Log.v(LOG_TAG, "onDetach");
}
}
Here is where I have the problem.
Logcat doesn't show the message "onActivityCreatedLibraryFragment". I have the methods onStart(), onResume(), onStop(), etc., with their "Log.v" and I have the same problem.
Thank you in advance for your help.
activity_library.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jgutierrezgil.bmusic.LibraryActivity"
tools:ignore="MergeRootFrame" />
fragment_library.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.jgutierrezgil.bmusic.LibraryActivity$PlaceholderFragment" >
</RelativeLayout>
EDIT 1: I have completed the code of LibraryFragment and I have added activity_library.xml and fragment_library.xml
It looks like you never actually add LibraryFragment to your code. You are only adding PlaceholderFragment, which is leftover from the tutorial you did.
In the onCreate() of your LibraryActivity, make the following changes:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
//.add(R.id.container, new PlaceholderFragment()).commit();
.add(R.id.container, new LibraryFragment()).commit();
}
}
The PlaceholderFragment is defined at the bottom of LibraryActivity and is meant as a dummy. The reason the proper layout is showing up is because you changed the inputted layout file to R.layout.fragment_library for the PlaceholderFragment, giving the appearance that it inflated the proper Fragment.