Android: Drawer menu + swipeView - android

I would like to implement a swipe views into my Sherlock fragments with the drawer menu.
I did it and it seems works fine, owever, there is a minor issue that i can't figure out.
So let's begin with some pices of my code:
MainActivity
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new TestFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Test title" };
// Generate subtitle
subtitle = new String[] { "Test subtitle" };
// Generate icon
icon = new int[] { R.drawable.action_about };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
TestFragment:
public class TestFragment extends SherlockFragment {
ViewPager mViewPager;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
PagerTabStrip pagerTabStrip = (PagerTabStrip) rootView.findViewById(R.id.pagerTabStrip);
testAdapter titleAdapter = new testAdapter(getFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(0);
return rootView;
}
}
testAdapter
public class testAdapter extends FragmentPagerAdapter {
private String titles[] = new String[]{"View1","View2"};
private Fragment frags[] = new Fragment[titles.length];
public systemAdapter(FragmentManager fm) {
super(fm);
frags[0] = new testSwipe1();
frags[1] = new testSwipe2();
}
#Override
public CharSequence getPageTitle (int position){
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
testSwipe1 and testSwipe2 are the same:
public class testSwipe1 extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.testswipe_layout, container, false);
ImageButton testImage = (ImageButton) rootView.findViewById(R.id.test);
//todo function image
return rootView;
}
}
Ok, the drawer works fine and if i tap on "test title" it inflate the layout with the swipe and i can see the image in the 2 test swipe views.
Owever, if i open back the drawer and tap again on "test title" i can see the swipe views without the images on my swipe fragment layout. If i put the device in landscape and back to portrait, the image on my swipe fragments come back! open drawer -> tap again on test title -> images disappear.... -> landscaper -> portrait -> image back.
The layouts defined are standard for drawer and swipeviews. inside the swipeviews fragments layout there is only an imageview. So the issue must be in the java part but i can't figure out where.
Any helps?

Try this: TestAdapter should implement FragmentStatePagerAdapter instead of FragmentsPagerAdapter. The reason is that the method getItem() is called differently. I had the same problem. Hope this helps.

I have edited the code given in here.
I just change the asyDrawerLayout.java file by implementing OnGestureListener interface with it's methods.
In the onCreate() I have set the gesture to the current context by adding following line.
gd = new GestureDetector(this, this);
Then I have Override the onTouchEvent() as follows
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//Registering TouchEvent with GestureDetector
return gd.onTouchEvent(event);
}
Then I have changed the onFling() as follows
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
//Defining Sensitivity
float sensitivity = 30;
//Swipe Left Check
if(e1.getX() - e2.getX() > sensitivity && mOpen){
closeDrawer();
return true;
}
//Swipe Right Check
if(e2.getX() - e1.getX() > sensitivity && !mOpen){
openDrawer();
return true;
}
return true;
}
Now it is working with Drawer menu + swipeView.
You can download my edited version from here.

Related

Android Fragments Overlapping each other

In my App, I have two Fragments: FragmentA and FragmentB which are loaded from my MainActivity by the help of an SlidingMenu.
When FragmentB is shown, it immediatelly starts an AsyncTask in background to load data from a server. The loading process is reflected by an active SwipeRefreshLayout to the user.
When loading is finished, the UI of FragmentB is refreshed with the loaded data, by the help of a delegate which is passed to MyAsyncClass.
I am now facing the following problem:
As soon as processFinish in my delegate is called, I am stopping the Refresh of the SwipeRefreshLayout by the help of swipeRefreshLayout.setRefreshing(false).
If the user is going back to FragmentA while background-Task is still in progress, it appears in about 20% of the cases, that FragmentB is still in background of FragmentA in the User Interface (see Screenshot below).
As you can see in the image, the FragmentA is shown (the text "No tracks played yet" is from FragmentA), but in the background you can see still the FragmentB.
As already mentioned, this is not in 100% of the cases, so it should not be an background/transparency issue. If I comment out the swipeRefreshLayout.setRefreshing(false), then the problem is not reproductible, but somehow I need to stop the SwipeRefreshLayout in case the user stays on FragmentB.
Any idea what causes this behaviour?
AsyncResponse-Interface:
public interface AsyncResponse {
void processFinish(String result);
}
FragmentB-Class:
public class FragmentB extends MyFragment implements SwipeRefreshLayout.OnRefreshListener, AsyncResponse {
private SwipeRefreshLayout swipeRefreshLayout;
private View view;
private RecyclerView recyclerView;
public FragmentB () {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.songs_list, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
// Set the adapter
Context context = view.getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.listinclude);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.divider));
List<Song> songsList = databaseHandler.getAllSongs();
setVisibilities(songsList);
this.recyclerViewAdapter = new RecyclerViewAdapter(songsList, mListener, false, false);
recyclerView.setAdapter(this.recyclerViewAdapter);
swipeRefreshLayout.setRefreshing(true);
receive();
return view;
}
private void setVisibilities(List<Song> songsList) {
ViewFlipper viewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlipper);
if (songsList.isEmpty() && viewFlipper.getDisplayedChild() == 0) {
viewFlipper.setDisplayedChild(1);
} else if (!songsList.isEmpty() && viewFlipper.getDisplayedChild() == 1) {
viewFlipper.setDisplayedChild(0);
}
}
#Override
public void onRefresh() {
if (MyOnlineHelper.isOnline(getContext())) {
receive();
} else {
swipeRefreshLayout.setRefreshing(false);
}
}
private void receive() {
new MyAsyncClass(this, getContext()).execute("receiving");
}
#Override
public void processFinish(String output) {
// refreshUI
swipeRefreshLayout.setRefreshing(false);
}
}
FragmentA-Class:
public class FragmentA extends MyFragment implements AsyncResponse {
private View view;
private RecyclerView recyclerView;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List<Song> songsList = myDatabaseHandler.getAllSongs();
view = inflater.inflate(R.layout.home_list, container, false);
// Set the adapter
Context context = view.getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.listinclude);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.divider));
setVisibilities(songsList);
this.recyclerViewAdapter = new RecyclerViewAdapter(songsList, mListener, false, true);
recyclerView.setAdapter(this.recyclerViewAdapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void setVisibilities(List<Song> songsList) {
ViewFlipper viewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlipper);
if (songsList.isEmpty() && viewFlipper.getDisplayedChild() == 0) {
viewFlipper.setDisplayedChild(1);
} else if (!songsList.isEmpty() && viewFlipper.getDisplayedChild() == 1) {
viewFlipper.setDisplayedChild(0);
}
}
#Override
public void processFinish(String output) {
// does something
}
}
MyAsyncClass:
public class MyAsyncClass extends AsyncTask<String, Integer, String> {
private AsyncResponse delegate;
private Context mContext;
private MyDatabaseHandler myDatabaseHandler;
public MyAsyncClass(AsyncResponse delegate, Context context) {
this.delegate = delegate;
this.mContext = context;
}
#Override
protected String doInBackground(String... params) {
// calling webservice and writing it to the database
}
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
super.onPostExecute(result);
}
}
MainActivity-Class:
public class MainActivity extends AppCompatActivity implements MyFragment.OnListFragmentInteractionListener, AsyncResponse {
private FragmentA fragmentA = new FragmentA();
private FragmentB fragmentB;
private NavigationView navigationView;
private DrawerLayout drawer;
private Toolbar toolbar;
// index to identify current nav menu item
private static int navItemIndex = 0;
public static String CURRENT_TAG = MyConstants.TAG_FRAGMENT_A;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA.setDatabaseHandler(this.myDatabaseHandler);
// Init UI
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fabSendButton = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.sliding_menu_item_activity_titles);
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = MyConstants.TAG_FRAGMENT_A;
loadHomeFragment();
}
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the activity_main_header_with_item content by replacing fragments
Fragment fragment = getFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getFragment() {
switch (navItemIndex) {
case 0:
return this.fragmentA;
case 1:
if (fragmentB == null) {
fragmentB = new FragmentB();
fragmentB.setDatabaseHandler(this.myDatabaseHandler);
}
return fragmentB;
default:
return this.fragmentA;
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the activity_main_header_with_item content with ContentFragment Which is our Inbox View;
case R.id.nav_A:
navItemIndex = 0;
CURRENT_TAG = MyConstants.TAG_FRAGMENT_A;
break;
case R.id.nav_B:
navItemIndex = 1;
CURRENT_TAG = MyConstants.TAG_FRAGMENT_B;
break;
default:
navItemIndex = 0;
}
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_header_with_item, menu);
return true;
}
}
Thanks to Prsnth Gettin High and this post ( When switch fragment with SwipeRefreshLayout during refreshing, fragment freezes but actually still work), wrapping the SwipeRefreshLayout in a FrameLayout helps, like that:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ViewFlipper
android:id="#+id/viewFlipper"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/listinclude"
layout="#layout/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:visibility="visible"/>
<include
android:id="#+id/emptyinclude"
layout="#layout/fragment_empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"/>
</ViewFlipper>
</android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>
try downcasting the fragment object to the specific fragment.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = getFragment();
FragmentA fragA;
FragmentB fragB;
if(fragment intanceof FragmentA)
{
fragA=(FragmentA) fragment;
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragA, FragmentA.TAG);
}
if(fragment instanceof FragmentB)
{
fragB=(FragmentB) fragment;
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragB, FragmentB.TAG);
}
fragmentTransaction.commit();
And may I ask why are you using a runnable to swap fragments?
try reusing the view. It may fix the issue.
`#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(view==null){view = inflater.inflate(R.layout.songs_list, container, false);}`

Navigation drawer with tabs in fragment

I am making an android app . I am using navigation drawer and some of the fragments which i am inflating using navigation drawer contain tab layout and some are normal fragments with textview .
I am facing 2 issues that when
i am opening the navigation drawer item with tabs afterthat its automatically keeping those tabs in the view even for the fragments that are not with tabs.
When i am opening the fragment with tabs 2nd time or more . Its duplicating the tabs. I mean if the first time no of tabs are 3 then the next time when i open the fragment the no. of tabs get doubled.
Activity with navigation drawer
public class MainFeedActivity extends FragmentActivity {
public DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawertitles;
LinearLayout drawerll;
String username;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainfeed);
username = getIntent().getExtras().getString("username").toString();
t = (TextView) findViewById(R.id.drawer_uname_tv);
t.setText(username);
mTitle = mDrawerTitle = getTitle();
mDrawertitles = getResources().getStringArray(R.array.array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
drawerll = (LinearLayout) findViewById(R.id.drawerll);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mDrawertitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(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(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(2);
}
}
#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) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return true;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
if (position == 0) {
Fragment fragment = new Home();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(drawerll);
}
else if (position == 1) {
Fragment fragment = new Statistics();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(drawerll);
} else {
Fragment fragment = new Help();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerLayout.closeDrawer(drawerll);
}
}
/*
*
* protected boolean isOnline() { ConnectivityManager cm =
* (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
* NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null &&
* netInfo.isConnectedOrConnecting()) { return true; } else { return false;
* } }
*/
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
}
Fragments
public class Home extends Fragment {
ActionBar.Tab Tab1, Tab2, Tab3;
Fragment fragmentTab1 = new Connected();
Fragment fragmentTab2 = new Disconnected();
Fragment fragmentTab3 = new AllDevices();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tabs, container, false);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowHomeEnabled(true);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(true);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab1 = actionBar.newTab().setText("Tab1");
Tab2 = actionBar.newTab().setText("Tab2");
Tab3 = actionBar.newTab().setText("Tab3");
Tab1.setTabListener(new TabListener(fragmentTab1));
Tab2.setTabListener(new TabListener(fragmentTab2));
Tab3.setTabListener(new TabListener(fragmentTab3));
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
actionBar.addTab(Tab3);
return view;
}
}
Fragments:
public class Help extends Fragment {
Button b;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.help, container, false);
setHasOptionsMenu(false);
return rootView;
}
}
I got the solution of my problems:
1st problem solved with the help of denvercoder9
when position!= 1, you need to change the actionBar Navigation Mode.... Android ActionBar: show/hide tabs dynamically? – denvercoder9
2nd problem's solution is
I need to use this
ActionBar actionBar = getActivity().getActionBar();
actionBar.removeAllTabs();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
in Home.java class
This resolved the problem of tabs duplication.
Thanks Stackoverflow for helping me :)
I was having the same issue so the solution is simple.
Ans 1: If you don't want Tabs in specific fragment then you can set the navigation bar as
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
Ans 2: Either remove the tabs from the home fragment each time u select it or u can check if required tabs already present there then dont add any more tabs in it like this
int tabCount= actionBar.getTabCount();
if(tabCount!=3){
Tab1 = actionBar.newTab().setText("Tab1");
Tab2 = actionBar.newTab().setText("Tab2");
Tab3 = actionBar.newTab().setText("Tab3");
Tab1.setTabListener(new TabListener(fragmentTab1));
Tab2.setTabListener(new TabListener(fragmentTab2));
Tab3.setTabListener(new TabListener(fragmentTab3));
actionBar.addTab(Tab1);
actionBar.addTab(Tab2);
actionBar.addTab(Tab3);
}
return view;
Hope it will solve your problem

setOnItemClickListener() in navigation drawer not working?

My .java code is :
public class welcome extends Activity
{
Button button1;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
mTitle = "JAVATECHIG.COM";
getActionBar().setTitle(mTitle);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerList.setClickable(true);
mDrawerList.setTextFilterEnabled(true);
// Getting reference to the ActionBarDrawerToggle
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();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("JAVATECHIG.COM");
Toast.makeText(getApplicationContext(), "Inside onDrawerOpened...", Toast.LENGTH_SHORT).show();
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
Toast.makeText(getApplicationContext(), "Inside ClickListener...", Toast.LENGTH_SHORT).show();
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
WebViewFragment rFragment = new WebViewFragment();
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
rFragment.setArguments(data);
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "After ArrayAdapter decraration...", Toast.LENGTH_SHORT).show();
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
}
protected String getUrl(int position) {
switch (position) {
case 0:
return "http://javatechig.com";
case 1:
return "http://javatechig.com/category/android/";
case 2:
return "http://javatechig.com/category/blackberry/";
case 3:
return "http://javatechig.com/category/j2me/";
case 4:
return "http://javatechig.com/category/sencha-touch/";
case 5:
return "http://javatechig.com/category/phonegap/";
case 6:
return "http://javatechig.com/category/java/";
default:
return "http://javatechig.com";
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Also my XML code is:
<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" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
/>
</android.support.v4.widget.DrawerLayout>
WebViewFragement.java code is:
public class WebViewFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
//WebView webView = (WebView)v.findViewById(R.id.webView);
//webView.getSettings().setJavaScriptEnabled(true);
//webView.loadUrl(url);
Toast.makeText(getActivity(),position+" ... "+url,Toast.LENGTH_SHORT).show();
return v;
}
}
.
.
My Question is whenever I run this code and click on any of the side menu option, it is not displaying anything. Means it is not going inside setOnItemClickListener().
I have tried all possible solution posted in this form but, these are not working.
Kindly help.
the error is probably in this line mDrawerList.setOnItemClickListener(new OnItemClickListener()) instead of implementing onItemClickListener implement list_item.setOnItemClickListener(new DrawerItemClickListener());

Drawer items Selected effect in android

Overview::
I have a navigation drawer
I am setting the textView color in the adapter when position is 0
to red
On selecting different element in the list that textView is set to
red and others to black
So at anytime only one textview must be set in red(selected
adapter) others in black
Also to note that the reason i am setting red for textview in
adapter when position is o because since its the first fragment shown when it is loaded for the first time
This must be un-selected when i am selecting other adapter which is not
happening
Code i use is::
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
setNavDrawerItemNormal();
title=(TextView) view.findViewById(R.id.title);
title.setTextColor(getApplicationContext().getResources().getColor(R.color.red));
}
}
public void setNavDrawerItemNormal()
{
for (int i=0; i< mDrawerList.getChildCount(); i++)
{
View v = mDrawerList.getChildAt(i);
TextView txtview = ((TextView) v.findViewById(R.id.title));
txtview.setTextColor(getApplicationContext().getResources().getColor(R.color.black));
}
}
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private GridView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (GridView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
setNavDrawerItemNormal();
title=(TextView) view.findViewById(R.id.title);
title.setTextColor(getApplicationContext().getResources().getColor(R.color.red));
}
}
public void setNavDrawerItemNormal()
{
for (int i=0; i< mDrawerList.getChildCount(); i++)
{
View v = mDrawerList.getChildAt(i);
TextView txtview = ((TextView) v.findViewById(R.id.title));
txtview.setTextColor(getApplicationContext().getResources().getColor(R.color.black));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FragmentOne();
break;
case 2:
fragment = new FragmentTwo();
break;
case 3:
fragment = new FragmentThree();
break;
case 4:
fragment = new FragmentFour();
break;
case 5:
fragment = new FragmentFive();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
NavDrawerListAdapter.java
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
if (position == 0)
{
txtTitle.setTextColor(context.getResources().getColor(R.color.red));
}
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
NOTE:: I Can achieve my objective with application variable, but i am trying to do without it, programatically
The main idea that You don't need to have any additional variables in adapter / activity, because Android component already have one for lists with single choice. The following solution works fine in your case:
Assume your layout (activity_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">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<GridView android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
Please note android:choiceMode="singleChoice" - that property will let the list track selected item by itself.
Remove all color setting code from the activity. Instead, use setChecked() to let the list know which item is selected:
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
private GridView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (GridView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setItemChecked(0, true); // NOTE: Set 0 item as checked!
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
android.R.drawable.ic_input_delete, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
// NOTE: new item is checked now
mDrawerList.setItemChecked(position, true);
}
}
...
}
In the adapter - just check if item is checked or not and set corresponding test color:
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
// TODO: Here ViewHolder pattern can be used or
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
// NOTE: check which item is Checked an set corresponding text color
if (((GridView)parent).isItemChecked(position)) {
txtTitle.setTextColor(context.getResources().getColor(R.color.red));
} else {
txtTitle.setTextColor(context.getResources().getColor(R.color.black));
}
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
With above code, text color will be changed only after pointer up (when you press item it's color will still hold old value). If you need it to change color during pressed state, then use the following code in the adapter:
// NOTE: check which item is Checked an set corresponding text color
if (((GridView)parent).isItemChecked(position)) {
//txtTitle.setTextColor(context.getResources().getColor(R.color.red));
txtTitle.setTextColor(context.getResources().getColorStateList(R.color.red_selector));
} else {
//txtTitle.setTextColor(context.getResources().getColor(R.color.black));
txtTitle.setTextColor(context.getResources().getColorStateList(R.color.black_selector));
}
And provide color/red_selector.xml and color/black_selector.xml. E.g. color/black_selector.xml should look the following way:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/red"/>
<item android:color="#color/black"/>
</selector>

NavigationDrawer main page and styling

this is the first application I am creating using a NavigationDrawer. I have a pretty simple question. How do I make the first page in the NavigationDrawer the main one? Also I'm not too familiar with formatting since this is my first time using the drawer so I would appreciate it if someone more familiar could tell me if I am doing it correctly. Right now each page just displays text but eventually it will do more. And one of my questions is how do I make it so that clicking a page in the drawer can open up a new page using a RelativeLayout for example. From my understanding Adapters are only for Views, would I create a completely new activity and call startActivity() in my iteration for the drawerclick? If so, is that efficient? Meaning will it take a long time for the page to load? My main activity is:
public class MainActivity extends Activity {
private String[] mPages;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
mPages = getResources().getStringArray(R.array.page_titles);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPages));
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
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) {
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment;
if(position == 0){
fragment = new OneFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 1){
fragment = new TwoFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 2){
fragment = new ThreeFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 3){
fragment = new FourFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPages[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
public static class OneFragment extends Fragment{
public OneFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("One");
return rootView;
}
}
public static class TwoFragment extends Fragment{
public TwoFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Two");
return rootView;
}
}
public static class ThreeFragment extends Fragment{
public ThreeFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Three");
return rootView;
}
}
public static class FourFragment extends Fragment{
public FourFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Four");
return rootView;
}
}
}
I apologize for the lengthy question, but the developer site wasn't helping out too much and I want to make sure I do this correctly the first time so I don't have to go back too much
Whatever you want to show needs to be within the child of the DrawerLayout. In your case, I think you would do a fragment transaction in onCreate() to put whatever fragment you want visible first inside of the content area.
if (savedInstanceState == null) {
fragment = new OneFragment();
// Insert the fragment by replacing any existing fragment
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
You can hold references to these fragments so you don't create a new instance of them each time the user makes a selection. You probably also want to make sure the new selection isn't the same as the current one, or else you will have extra transactions you don't need.
For opening a "new page", you want to use startActivity() and show another activity with it's own layout. Generally speaking, don't be concerned about how long it takes an Activity to load unless you are specifically doing some meaningful work (like loading a bunch of data out of a database).
Lastly, Adapters are specifically for AdapterViews (like ListView) and are an entirely different matter. They are used in conjunction with specific UI components to generate child views for representing potentially large data sets and which can be recycled for efficiency reasons. I suggest you watch The World of ListView if you want more information/clarity about that.

Categories

Resources