Using fragments from navigation drawer to overlay activity - android

I am having trouble laying a fragment on top of my existing activity. What I am attempting to accomplish is as follows: Open app -> mapView is created -> navigation drawer is created -> button on navigation drawer opens new fragment laying on top on mapView (while mapView not being visible). What is happening is the layout for the fragment is showing, but the white space of the layout is transparent and I am still able to use the map. Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private MapView mapView;
private LocationListener locationListener;
private GeometryLayer locationLayer;
private Timer locationTimer;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setMap();
initDrawer(savedInstanceState);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SelectItem(position);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#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 false;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new ProfileFragment();
args.putString(ProfileFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(ProfileFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 1:
fragment = new ProfileFragment();
args.putString(ProfileFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(ProfileFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 4:
fragment = new SettingsFragment();
args.putString(SettingsFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(SettingsFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
default:
break;
}
fragment.setArguments(args);
android.app.FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onStart() {
super.onStart();
// 4. Start the map - mandatory.
mapView.startMapping();
// Create layer for location circle
locationLayer = new GeometryLayer(mapView.getLayers().getBaseProjection());
mapView.getComponents().layers.addLayer(locationLayer);
// add GPS My Location functionality
final MyLocationCircle locationCircle = new MyLocationCircle(locationLayer);
initGps(locationCircle);
// Run animation
locationTimer = new Timer();
locationTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
locationCircle.update(mapView.getZoom());
}
}, 0, 50);
}
#Override
protected void onStop() {
// Stop animation
locationTimer.cancel();
// Remove created layer
mapView.getComponents().layers.removeLayer(locationLayer);
// remove GPS support, otherwise we will leak memory
deinitGps();
// Note: it is recommended to move startMapping() call to onStart method and implement onStop method (call MapView.stopMapping() from onStop).
mapView.stopMapping();
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
protected void initGps(final MyLocationCircle locationCircle) {
final Projection proj = mapView.getLayers().getBaseLayer().getProjection();
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationCircle.setLocation(proj, location);
locationCircle.setVisible(true);
// recenter automatically to GPS point
// TODO in real app it can be annoying this way, add extra control that it is done only once
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(location.getLongitude(), location.getLatitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.debug("GPS onStatusChanged "+provider+" to "+status);
}
#Override
public void onProviderEnabled(String provider) {
Log.debug("GPS onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider) {
Log.debug("GPS onProviderDisabled");
}
};
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
for(String provider : providers){
locationManager.requestLocationUpdates(provider, 10000, 100, locationListener);
}
}
protected void deinitGps() {
// remove listeners from location manager - otherwise we will leak memory
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
// adjust zooming to DPI, so texts on rasters will be not too small
// useful for non-retina rasters, they would look like "digitally zoomed"
private void adjustMapDpi() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float dpi = metrics.densityDpi;
// following is equal to -log2(dpi / DEFAULT_DPI)
float adjustment = (float) - (Math.log(dpi / DisplayMetrics.DENSITY_HIGH) / Math.log(2));
Log.debug("adjust DPI = "+dpi+" as zoom adjustment = "+adjustment);
mapView.getOptions().setTileZoomLevelBias(adjustment / 2.0f);
}
private void addCartoDbLayer() {
// 5.1 Define styles for all possible geometry types
int color = Color.BLUE;
int minZoom = 5;
final Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.point);
final StyleSet<PointStyle> pointStyleSet = new StyleSet<PointStyle>();
PointStyle pointStyle = PointStyle.builder().setBitmap(pointMarker).setSize(0.05f).setColor(color).setPickingSize(0.2f).build();
pointStyleSet.setZoomStyle(minZoom, pointStyle);
final StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>();
LineStyle lineStyle = LineStyle.builder().setWidth(0.04f).setColor(Color.WHITE).build();
lineStyleSet.setZoomStyle(minZoom, lineStyle);
final StyleSet<PolygonStyle> polygonStyleSet = new StyleSet<PolygonStyle>(null);
PolygonStyle polygonStyle = PolygonStyle.builder().setColor(0xFFFF6600 & 0x80FFFFFF).setLineStyle(lineStyle).build();
polygonStyleSet.setZoomStyle(minZoom, polygonStyle);
String account = "bitciv";
String table = "units"; // kihelkonnad_1897, maakond_20120701
String columns = "cartodb_id,name,iso2,pop2005,area,the_geom_webmercator"; // NB! always include cartodb_id and the_geom_webmercator
//String columns = "cartodb_id,job,the_geom_webmercator";
int limit = 5000; // max number of objects
String sql = "SELECT "+columns+" FROM "+table+" WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT "+limit;
// String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE type in ('trunk','primary') AND the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
// String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
CartoDbDataSource cartoDataSource = new CartoDbDataSource(mapView.getLayers().getBaseLayer().getProjection(), account, sql) {
#Override
protected Label createLabel(Map<String, String> userData) {
StringBuffer labelTxt = new StringBuffer();
for (Map.Entry<String, String> entry : userData.entrySet()){
labelTxt.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
return new DefaultLabel("Data:", labelTxt.toString());
}
#Override
protected StyleSet<PointStyle> createPointStyleSet(Map<String, String> userData, int zoom) {
return pointStyleSet;
}
#Override
protected StyleSet<LineStyle> createLineStyleSet(Map<String, String> userData, int zoom) {
return lineStyleSet;
}
#Override
protected StyleSet<PolygonStyle> createPolygonStyleSet(Map<String, String> userData, int zoom) {
return polygonStyleSet;
}
};
GeometryLayer cartoLayerTrunk = new GeometryLayer(cartoDataSource);
mapView.getLayers().addLayer(cartoLayerTrunk);
}
private void setMap(){
// enable logging for troubleshooting - optional
Log.enableAll();
Log.setTag("hellomap");
// 1. Get the MapView from the Layout xml - mandatory
mapView = (MapView) findViewById(R.id.mapView);
// Optional, but very useful: restore map state during device rotation,
// it is saved in onRetainNonConfigurationInstance() below
Components retainObject = (Components) getLastNonConfigurationInstance();
if (retainObject != null) {
// just restore configuration and update listener, skip other initializations
mapView.setComponents(retainObject);
return;
} else {
// 2. create and set MapView components - mandatory
mapView.setComponents(new Components());
}
// 3. Define map layer for basemap - mandatory.
// Here we use MapQuest open tiles.
// We use online data source for the tiles and the URL is given as template. Almost all online tiled maps use EPSG3857 projection.
RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");
RasterLayer mapLayer = new RasterLayer(dataSource, 0);
mapView.getLayers().setBaseLayer(mapLayer);
adjustMapDpi();
// Show performance indicator
//mapView.getOptions().setFPSIndicator(true);
// Increase raster tile download speed by doing 4 downloads in parallel
//mapView.getOptions().setRasterTaskPoolSize(4);
// set initial map view camera - optional. "World view" is default
// Location: San Francisco
// NB! it must be in base layer projection (EPSG3857), so we convert it from lat and long
mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));
// rotation - 0 = north-up
mapView.setMapRotation(0f);
// zoom - 0 = world, like on most web maps
mapView.setZoom(16.0f);
// tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
mapView.setTilt(65.0f);
// Activate some mapview options to make it smoother - optional
mapView.getOptions().setPreloading(true);
mapView.getOptions().setSeamlessHorizontalPan(true);
mapView.getOptions().setTileFading(true);
mapView.getOptions().setKineticPanning(true);
mapView.getOptions().setDoubleClickZoomIn(true);
mapView.getOptions().setDualClickZoomOut(true);
// set sky bitmap - optional, default - white
mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setSkyOffset(4.86f);
mapView.getOptions().setSkyBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.sky_small));
// Map background, visible if no map tiles loaded - optional, default - white
mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setBackgroundPlaneBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.background_plane));
mapView.getOptions().setClearColor(Color.WHITE);
// configure texture caching - optional, suggested
mapView.getOptions().setTextureMemoryCacheSize(40 * 1024 * 1024);
mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);
// define online map persistent caching - optional, suggested. Default - no caching
mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
// set persistent raster cache limit to 100MB
mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);
/* // 5. Add simple marker to map.
// define marker style (image, size, color)
Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker);
MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setColor(Color.WHITE).build();
// define label what is shown when you click on marker
Label markerLabel = new DefaultLabel("San Francisco", "Here is a marker");
// define location of the marker, it must be converted to base map coordinate system
MapPos markerLocation = mapLayer.getProjection().fromWgs84(-122.416667f, 37.766667f);
// create layer and add object to the layer, finally add layer to the map.
// All overlay layers must be same projection as base layer, so we reuse it
MarkerLayer markerLayer = new MarkerLayer(mapLayer.getProjection());
markerLayer.add(new Marker(markerLocation, markerLabel, markerStyle, null));
mapView.getLayers().addLayer(markerLayer); */
// add event listener
MyMapEventListener mapListener = new MyMapEventListener(this, mapView);
mapView.getOptions().setMapListener(mapListener);
// 5. Add CartoDB vector layer to map
addCartoDbLayer();
}
private void initDrawer(Bundle savedInstanceState){
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerList.setBackgroundResource(R.color.white);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Profile", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Messages", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Statistics", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Settings", R.drawable.ic_action_labels));
dataList.add(new DrawerItem("Invite", R.drawable.ic_action_search));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
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(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(0);
}
}
}
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" >
<com.nutiteq.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
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>

If I understand correctly, what is happening is that the white spaces of your top most Fragment are not capturing click events. To solve this, you need to make the root ViewGroup of the top most Fragment clickable. If the secondFragmentto be added takes up the whole or most of the screen, it is better to call remove() instead of add() in your FragmentTransaction to avoid this issue completely.

Related

wordpress reader declangao and navigation drawer

I'm new in android programmation. I'm triyng to implement a navigation drawer in wordpress reader declan gao project. I'm getting crazy. He loads a list of wordpress posts and display it with cardview. If I put all necessary in activity_main My navigation drawer appears below cardview posts and I can't interact with it. If I try to put it in TabLayoutFragment i have a lot of errors!!!
Is there someone who can help me to insert navigation drawer in the right place!!!
Than you so much!!!
This is MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewFragment.PostListListener, PostFragment.PostListener,
TabLayoutFragment.TabLayoutListener, SearchResultFragment.SearchResultListener
{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String TAB_LAYOUT_FRAGMENT_TAG = "TabLayoutFragment";
public static final String POST_FRAGMENT_TAG = "PostFragment";
private FragmentManager fm = null;
private TabLayoutFragment tlf;
private PostFragment pf;
private SearchResultFragment srf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// Setup fragments
tlf = new TabLayoutFragment();
pf = new PostFragment();
srf = new SearchResultFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.content, pf, POST_FRAGMENT_TAG);
ft.add(android.R.id.content, tlf, TAB_LAYOUT_FRAGMENT_TAG);
ft.hide(pf);
ft.commit();
}
/**
* Invoked when a post in the list is selected
*
* #param post Selected Post object
*/
#Override
public void onPostSelected(Post post, boolean isSearch) {
// Find the fragment in order to set it up later
pf = (PostFragment) getSupportFragmentManager().findFragmentByTag(POST_FRAGMENT_TAG);
// Set necessary arguments
Bundle args = new Bundle();
args.putInt("id", post.getId());
args.putString("title", post.getTitle());
args.putString("date", post.getDate());
args.putString("author", post.getAuthor());
args.putString("content", post.getContent());
args.putString("url", post.getUrl());
//args.putString("thumbnailUrl", post.getThumbnailUrl());
args.putString("featuredImage", post.getFeaturedImageUrl());
// Configure PostFragment to display the right post
pf.setUIArguments(args);
// Show the fragment
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (!isSearch) { // Hide TabLayoutFragment if this is not search result
ft.hide(tlf);
} else { // Otherwise, hide the search result, ie. SearchResultFragment.
ft.hide(srf);
}
ft.show(pf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when a search query is submitted
*
* #param query Selected Post object
*/
#Override
public void onSearchSubmitted(String query) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// Send query to fragment using factory method
srf = SearchResultFragment.newInstance(query);
ft.add(android.R.id.content, srf);
ft.hide(tlf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when comment menu is selected
*
* #param id ID of the article, assigned by WordPress
*/
#Override
public void onCommentSelected(int id) {
Bundle args = new Bundle();
args.putInt("id", id);
// Setup CommentFragment to display the right comments page
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
ft.hide(pf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Intercept back button event, reset ActionBar if necessary
*/
#Override
public void onBackPressed() {
resetActionBarIfApplicable();
super.onBackPressed();
}
/**
* Simulate a back button press when home is selected
*/
#Override
public void onHomePressed() {
resetActionBarIfApplicable();
fm.popBackStack();
}
/**
* Reset TabLayoutFragment's ActionBar if necessary
*/
private void resetActionBarIfApplicable() {
Log.d(TAG, "SearchResultFragment is visible: " + srf.isHidden());
if (srf.isVisible()) {
tlf.resetActionBar();
}
}
// Commented out coz we will let fragments handle their own Options Menus
//#Override
//public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
//}
}
This is activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<android.support.v7.widget.Toolbar-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:background="#color/colorPrimary"-->
<!--android:theme="#style/ThemeOverlay.AppCompat.Dark"-->
<!--android:id="#+id/toolbar">-->
<!--</android.support.v7.widget.Toolbar>-->
<!--<FrameLayout-->
<!--android:id="#+id/container"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent">-->
<!--</FrameLayout>-->
This is TabLayoutFragment.java
/**
* Fragment to display TabLayout and ViewPager.
* Activities that contain this fragment must implement the
* {#link TabLayoutFragment.TabLayoutListener} interface
* to handle interaction events.
*/
public class TabLayoutFragment extends Fragment implements SearchView.OnQueryTextListener {
private static final String TAG = "TabLayoutFragment";
private ProgressDialog mProgressDialog;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private Toolbar toolbar;
private SearchView searchView;
private MenuItem searchMenuItem;
// List of all categories
protected static ArrayList<Category> categories = null;
private TabLayoutListener mListener;
public TabLayoutFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Stops onDestroy() and onCreate() being called when the parent
// activity is destroyed/recreated on configuration change
setRetainInstance(true);
// Display a search menu
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
// Preload 1 page to either side of the current page
mViewPager.setOffscreenPageLimit(1);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadCategories();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d(TAG, "onCreateOptionsMenu()");
inflater.inflate(R.menu.menu_main, menu);
// Create expandable & collapsible SearchView
SearchManager searchManager = (SearchManager)
getActivity().getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false); // Expanded by default
//searchView.requestFocus();
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_search) {
searchView.requestFocus();
}
return true;
}
/**
* Reset the ActionBar to show proper menu and collapse SearchView
*/
protected void resetActionBar() {
((MainActivity)getActivity()).setSupportActionBar(toolbar);
searchMenuItem.collapseActionView();
}
/**
* Download categories and create tabs
*/
private void loadCategories() {
// Display a progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getString(R.string.loading_categories));
// User cannot dismiss it by touching outside the dialog
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
// Make a request to get categories
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Config.CATEGORY_URL,
null,
new Response.Listener<JSONObject>() {
// Request succeeded
#Override
public void onResponse(JSONObject jsonObject) {
mProgressDialog.dismiss();
// Get categories from JSON data
categories = JSONParser.parseCategories(jsonObject);
RecyclerViewFragmentPagerAdaptor adaptor = new
RecyclerViewFragmentPagerAdaptor(getChildFragmentManager(), categories);
mViewPager.setAdapter(adaptor);
mTabLayout.setupWithViewPager(mViewPager);
}
},
// Request failed
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "----- Volley Error -----");
mProgressDialog.dismiss();
// Show an INDEFINITE Snackbar. New in design support lib v22.2.1.
Snackbar.make(mTabLayout, R.string.error_load_categories,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.action_retry,
new View.OnClickListener() {
#Override
public void onClick(View v) {
loadCategories();
}
}).show();
}
});
// Add the request to request queue
AppController.getInstance().addToRequestQueue(request);
}
#Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus(); // Hide soft keyboard
mListener.onSearchSubmitted(query); // Deal with fragment transaction on MainActivity
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (TabLayoutListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
"must implement PostListListener");
}
}
// Interface used to communicate with MainActivity
public interface TabLayoutListener {
void onSearchSubmitted(String query);
}
}
This is FragmentTabLayout.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.declangao.wordpressreader.app.TabLayoutFragment">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|enterAlways"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"
style="#style/CustomTabLayout"/>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
This is RecyclerViewFragment.java
/**
* Fragment to display a RecyclerView.
* Activities that contain this fragment must implement the
* {#link RecyclerViewFragment.PostListListener} interface
* to handle interaction events.
*/
public class RecyclerViewFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "RecyclerViewFragment";
protected static final String CAT_ID = "id";
protected static final String QUERY = "query";
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
private MyRecyclerViewAdaptor mAdaptor;
private LinearLayoutManager mLayoutManager;
// Widget to show user a loading message
private TextView mLoadingView;
// List of all posts in the ListView
private ArrayList<Post> postList = new ArrayList<>();
// A flag to keep track if the app is currently loading new posts
private boolean isLoading = false;
private int mPage = 1; // Page number
private int mCatId; // Category ID
private int mPreviousPostNum = 0; // Number of posts in the list
private int mPostNum; // Number of posts in the "new" list
private String mQuery = ""; // Query string used for search result
// Flag to determine if current fragment is used to show search result
private boolean isSearch = false;
// Keep track of the list items
private int mPastVisibleItems;
private int mVisibleItemCount;
private PostListListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param id ID of the category.
* #return A new instance of RecyclerViewFragment.
*/
public static RecyclerViewFragment newInstance(int id) {
RecyclerViewFragment fragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putInt(CAT_ID, id);
fragment.setArguments(args);
return fragment;
}
/**
* Use this factory method to create a new instance of this fragment
* using the provided parameters to display search result.
*
* #param query search query.
* #return A new instance of RecyclerViewFragment.
*/
public static RecyclerViewFragment newInstance(String query) {
RecyclerViewFragment fragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putString(QUERY, query);
fragment.setArguments(args);
return fragment;
}
public RecyclerViewFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCatId = getArguments().getInt(CAT_ID, -1);
mQuery = getArguments().getString(QUERY, "");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);
// Pull to refresh layout
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mLoadingView = (TextView) rootView.findViewById(R.id.text_view_loading);
mLayoutManager = new LinearLayoutManager(getActivity());
// Pull to refresh listener
mSwipeRefreshLayout.setOnRefreshListener(this);
// RecyclerView adaptor for Post object
mAdaptor = new MyRecyclerViewAdaptor(postList, new MyRecyclerViewAdaptor.OnItemClickListener() {
#Override
public void onItemClick(Post post) {
mListener.onPostSelected(post, isSearch);
}
});
mRecyclerView.setHasFixedSize(true); // Every row in the list has the same size
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdaptor);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
// Automatically load new posts if end of the list is reached
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//super.onScrolled(recyclerView, dx, dy);
mVisibleItemCount = mLayoutManager.getChildCount();
mPastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
int totalItemCount = mLayoutManager.getItemCount();
if (mPostNum > mPreviousPostNum && !postList.isEmpty() && mVisibleItemCount != 0 &&
totalItemCount > mVisibleItemCount && !isLoading &&
(mVisibleItemCount + mPastVisibleItems) >= totalItemCount) {
loadNextPage();
// Update post number
mPreviousPostNum = mPostNum;
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadFirstPage();
}
/**
* Load the first page of a category
*/
public void loadFirstPage(){
mPage = 1; // Reset page number
if (postList.isEmpty()) {
showLoadingView();
// Reset post number to 0
mPreviousPostNum = 0;
loadPosts(mPage, false);
} else {
hideLoadingView();
}
}
/**
* Load the next page of a category
*/
public void loadNextPage(){
mPage ++;
loadPosts(mPage, true);
}
/**
* Load posts from a specific page number
*
* #param page Page number
* #param showLoadingMsg Flag to determine whether to show Toast loading msg to inform the user
*/
private void loadPosts(int page, final boolean showLoadingMsg) {
Log.d(TAG, "----------------- Loading category id " + mCatId +
", page " + String.valueOf(page));
isLoading = true;
if (showLoadingMsg) {
Toast.makeText(getActivity(), getString(R.string.loading_articles),
Toast.LENGTH_LONG).show();
}
// Construct the proper API Url
String url;
if (!mQuery.isEmpty()) { // Not empty mQuery means this list is for search result.
isSearch = true;
url = Config.BASE_URL + "?json=get_search_results&search=" + mQuery +
"&page=" + String.valueOf(page);
} else { // Empty mQuery means normal list of posts
isSearch = false;
if (mCatId == 0) { // The "All" tab
url = Config.BASE_URL + "?json=get_posts&page=" + String.valueOf(page);
} else { // Everything else
isSearch = false;
url = Config.BASE_URL + "?json=get_category_posts&category_id=" + String.valueOf(mCatId)
+ "&page=" + String.valueOf(page);
}
}
Log.d(TAG, url);
// Request post JSON
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
mSwipeRefreshLayout.setRefreshing(false); // Stop when done
// Parse JSON data
postList.addAll(JSONParser.parsePosts(jsonObject));
// A temporary workaround to avoid downloading duplicate posts in some
// rare circumstances by converting ArrayList to a LinkedHashSet without
// losing its order
Set<Post> set = new LinkedHashSet<>(postList);
postList.clear();
postList.addAll(new ArrayList<>(set));
mPostNum = postList.size(); // The newest post number
Log.d(TAG, "Number of posts: " + mPostNum);
mAdaptor.notifyDataSetChanged(); // Display the list
// Set ListView position
if (RecyclerViewFragment.this.mPage != 1) {
// Move the article list up by one row
// We don't actually need to add 1 here since position starts at 0
mLayoutManager.scrollToPosition(mPastVisibleItems + mVisibleItemCount);
}
// Loading finished. Set flag to false
isLoading = false;
hideLoadingView();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
isLoading = false;
hideLoadingView();
mSwipeRefreshLayout.setRefreshing(false);
volleyError.printStackTrace();
Log.d(TAG, "----- Error: " + volleyError.getMessage());
// Show a Snackbar with a retry button
Snackbar.make(mRecyclerView, R.string.error_load_posts,
Snackbar.LENGTH_LONG).setAction(R.string.action_retry,
new View.OnClickListener() {
#Override
public void onClick(View v) {
//loadFirstPage();
loadPosts(mPage, true);
}
}).show();
}
});
// Set timeout to 10 seconds instead of the default value 5 since my
// crappy server is quite slow
request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Add request to request queue
AppController.getInstance().addToRequestQueue(request, TAG);
}
#Override
public void onRefresh() {
// Clear the list
postList.clear();
mAdaptor.notifyDataSetChanged();
loadFirstPage();
}
/**
* Show the loading view and hide the list
*/
private void showLoadingView() {
mRecyclerView.setVisibility(View.INVISIBLE);
mLoadingView.setVisibility(View.VISIBLE);
}
/**
* Hide the loading view and show the list
*/
private void hideLoadingView() {
mLoadingView.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (PostListListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
"must implement PostListListener");
}
}
// Interface used to communicate with MainActivity
public interface PostListListener {
void onPostSelected(Post post, boolean isSearch);
}
}
This is fragment_recyclerview.xml
<FrameLayout 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"
tools:context="me.declangao.wordpressreader.app.RecyclerViewFragment">
<!-- Article list -->
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/swipe_refresh_layout" >
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recycler_view" />
</android.support.v4.widget.SwipeRefreshLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text_view_loading"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"
android:text="#string/loading_articles"/>

Zoom to the current location not working with navigation drawer

I'm developing an Android Application which is consists of a Navigation drawer and a Google Map. I have successfully developed my Navigation Drawer and connect my Map into it. The thing is I need my Map to Zoom to the current location.
Here is the code I used in MapsActivity.java.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
Location currentLocation = getMyLocation(); // Calling the getMyLocation method
if(currentLocation!=null){
LatLng currentCoordinates = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13.0f));
}
}
Here I implemented getMyLocation() method.
//Zoom to the current location
private Location getMyLocation() {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Location wasn't found, check the next most accurate place for the current location
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// Finds a provider that matches the criteria
String provider = lm.getBestProvider(criteria, true);
// Use the provider to get the last known location
myLocation = lm.getLastKnownLocation(provider);
}
return myLocation;
}
Here is How I gave MapsFragment in to NavigatioDrawerActivity.
fragment = new MapFragment();
When I run this alone (Insert intent filter to MapsActivity in Manifest) it works perfect. But, when I'm running the Nvigation Drawer as MainActivity this function is not working. Only the default Map is loading.
What should I do?
-edit-
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
My Maps.xml is like this.
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
My whole MapsActivity.java
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
initializaMap(rootView, savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void initializaMap(View rootView, Bundle savedInstanceState){
MapsInitializer.initialize(MapsActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this)) {
case ConnectionResult.SUCCESS:
mapView = (MapView) rootView.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9270786, 79.861243), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onMyLocationChange(Location location) {
}
}
Here is my NavigationDrawer.java
public class NavigationDrawer extends ActionBarActivity {
private GoogleMap mMap;
String[] menutitles;
TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
private LinearLayout mLenear;
static ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_NavigationDrawer);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
mLenear = (LinearLayout)findViewById(R.id.left_drawer);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFA500")));
imageView=(ImageView)findViewById(R.id.profPic);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.ic_prof);
imageView.setImageBitmap(getCircleBitmap(bitmap));
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().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
updateDisplay(0);
}
initializaMap(savedInstanceState);
}
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(Extract.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(Extract.this)) {
case ConnectionResult.SUCCESS:
MapView mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9192, 79.8950), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
//Circle Image
public static Bitmap getCircleBitmap(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Paint.Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Paint.Style.STROKE);
p.setColor(Color.WHITE);
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 2, (h / 2) + 2, radius, p);
return output;
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
// fragment = new MapFragment();
//break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mLenear);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_extract, 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(mLenear);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/** * 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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
try this ..
map.animateCamera(CameraUpdateFactory.newLatLngZoom((sydney), 13.0f));
you have not given by in float. so its not working.. try this..
try this
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13));
In XML
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In JAVA Activity
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(MainActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
call like this
initializaMap(savedInstanceState);
it will not work because the navigation drawer takes a fragment and you are initializing :
fragment = new MapFragment();
so it takes the MapFragment default layout .
you must to change the updateDisplay to takes an activity not a fragment . In another words change the navigation drawer to activities instead of fragments

Navigation drawer hanged for 2 seconds while selecting one option

I have a navigation drawer in which i have many fragments which come on selecting any item of navigation drawer. On one item I am showing a map. I don't know why on selecting that item navigation drawer hangs for 2-3 seconds and then drawer close. I want it smooth like other items in navigation drawer.
Here is my code for navigation drawer in MainActivity:
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, 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");
}
}
And here is the code of fragment on which the drawer hangs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
mPlaceType = getResources().getStringArray(R.array.place_type);
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) rootView.findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) rootView.findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
dialog.show();
}else {
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager =
(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
return rootView;
}
I also faced problem like that.
That totally work for me. Hope will help you
In your code,
In displayView function, put all codes in Runnable.
mPendingThread = new Runnable() {
#Override
public void run() {
//Here is all your code
switch(position){
.........
.........
}
};
In onCreate method,
mHandler = new Handler();
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
#Override
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
if (mPendingThread != null) {
mHandler.post(mPendingThread);
mPendingThread = null;
}
}
/** Called when a drawer is opened */
#Override
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);

Navigational drawer doesn't open when not data network android

I am using Navigational drawer for showing ExpandableListview . Every thing is working perfect except one ... When no data network the drawer doesn't opens ( when clicked on the drawer icon nothing happens )
There is NO code explicitly to OPEN drawer when network is available .
MainActivity.java
public class MainActivity extends Activity implements OnQueryTextListener {
public int CURRENT_THEME;
/* Google Analytics*/
Button btn_trackEvent, btn_trackCrash;
EasyTracker easyTracker = null;
GoogleAnalytics googleAnalytics;
StandardExceptionParser exceptionParser;
/* END GOOGLE ANALYTICS */
/* shared preference */
SharedPreferences sharedExpListView;
SharedPreferences.Editor editorExpList;
/* end of shared preference */
private DrawerLayout mDrawerLayout;
//private ListView expListView;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild,emptyChildren;
List<String> list_cat_name,list_cat_id,list_setting;
private HashMap<String, ArrayList<String>> emptyChild;
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 TextView mStatusView;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
JSONArray cat = null;
// Hashmap for ListView
// ArrayList<HashMap<String, String>> catList;
int error_flag = 0; // 0 normal, 1 internet connvettion 2Server Error
private TextView main_error;
private TextView textView;
String FavCount = "0";
/* for push */
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name = "All";
public static String email = "newsfirst#gmail.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Let's get rid of the app icon here
ActionBar actionBar = getActionBar();
actionBar.setIcon(null);
actionBar.setTitle("");
super.onCreate(savedInstanceState);
//overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
//LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View view = inflator.inflate(R.layout.action_bar_custom, null);
setContentView(R.layout.activity_main);
// Google Analytics
googleAnalytics = GoogleAnalytics.getInstance(this);
googleAnalytics.setDryRun(true);
googleAnalytics.getLogger().setLogLevel(LogLevel.VERBOSE);
easyTracker = EasyTracker.getInstance(MainActivity.this);
easyTracker.set(Fields.SCREEN_NAME, "MainActivity");
easyTracker.send(MapBuilder.createAppView().build());
exceptionParser = new StandardExceptionParser(MainActivity.this, null);
// End Google Analytics
/* get polling webservice*/
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
/* shared preference */
sharedExpListView=this.getSharedPreferences("sharedExpListView", MODE_PRIVATE);
editorExpList=sharedExpListView.edit();
// 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);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], "", navMenuIcons
.getResourceId(0, -1), "0"));
FavCount = String.valueOf(All_link.getFavRowCount(MainActivity.this));
// initialize Expandable listview
expListView = (ExpandableListView) findViewById(R.id.list_slidermenu);
expListView.setGroupIndicator(null);
list_cat_name = new ArrayList<String>();
list_cat_id = new ArrayList<String>();
list_setting = new ArrayList<String>();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
emptyChild = new HashMap<String, ArrayList<String>>();
new GetCatList().execute();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
0, // nav drawer open - description for
// accessibility
0 // nav drawer close - description for
// accessibility
) {
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
//Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0, "0");
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.e("position", "karpo "+position);
TextView txt_id = (TextView) view.findViewById(R.id.txt_id);
String catid = txt_id.getText().toString();
TextView txt_title = (TextView) view.findViewById(R.id.title);
All_link.GLOBAL_TITLE = "";
All_link.GLOBAL_TITLE = txt_title.getText().toString();
// display view for selected nav drawer item
if (!catid.isEmpty())
displayView(position, catid);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Toast.makeText(this, "Selected Item: " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
// 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_search:
*
* 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(expListView);
// menu.findItem(R.id.action_search).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position, String id) {
// update the main content by replacing fragments
Fragment fragment = null;
Log.e("POSITION", String.valueOf(id));
int position_id = Integer.parseInt(id);
switch (position_id) {
case 0:
// update selected item and title, then close the drawer
try{
fragment = new HomeFragment();
easyTracker.send(MapBuilder.createEvent("Menu Click", "Fragment", "HomeFragment", null).build());
}
catch(Exception e){
easyTracker.send(MapBuilder.createException(exceptionParser.getDescription(Thread.currentThread().getName(), e), false).build());
}
break;
default:
fragment = new CategoryFragment(id);
Log.e("category id","karcat "+id);
break;
}
// update selected item and title, then close the drawer
// expListView.setItemChecked(position, true);
// expListView.setSelection(position);
// //setTitle(navMenuTitles[position]);
// mDrawerLayout.closeDrawer(expListView);
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
expListView.setItemChecked(position, true);
expListView.setSelection(position);
// setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(expListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCatList extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
//expListView.setVisibility(8);
super.onPreExecute();
// Adding group data
listDataHeader.add("Home");
listDataHeader.add("News Category");
listDataHeader.add("My Favourites");
listDataHeader.add("Manage Notifications");
listDataHeader.add("Send Your Story");
listDataHeader.add("News on WhatsApp");
listDataHeader.add("About NewsFirst");
listDataHeader.add("Contact NewsFirst");
listDataHeader.add("Share this App");
listDataHeader.add("Rate this App");
listDataHeader.add("Settings");
listDataChild.put(listDataHeader.get(0), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(2), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(3), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(4), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(5), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(6), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(7), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(8), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(9), new ArrayList<String>()); // No child
list_setting.add("FAQs");
list_setting.add("Privacy Policy");
list_setting.add("Terms & Conditions");
listDataChild.put(listDataHeader.get(10), list_setting); // With child
}
#Override
protected Void doInBackground(String... params) {
if (NetworkCheck.isNetworkAvailable(getApplicationContext()) == true) {
//navDrawerItems = new ArrayList<NavDrawerItem>();
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(All_link.CATEGORY_URL,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
cat = jsonObj.getJSONArray(All_link.TAG_NEWS);
String err = jsonObj.getString(All_link.TAG_ERROR);
Log.e("------>Error", String.valueOf(err));
if (err.equals("1")) {
} else {
// looping through All Contacts
for (int i = 0; i < cat.length(); i++) {
JSONObject c = cat.getJSONObject(i);
String cat_id = c.getString(All_link.TAG_CAT_ID);
String cat_name = c
.getString(All_link.TAG_CAT_NAME);
String image_icon = c.getString("image_icon");
list_cat_name.add(cat_name);
list_cat_id.add(cat_id);
}
// saving cat_name with cat id in shared preference
for (int i = 0; i <list_cat_name.size(); i++) {
editorExpList.putString(list_cat_name.get(i), list_cat_id.get(i));
editorExpList.commit();
}
// End saving cat_name with cat id in shared preference
listDataChild.put(listDataHeader.get(1), list_cat_name); // With child
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e("Network Error", "Internet Connection Error");
error_flag = 1;
// error = "Internet Connection Error";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (error_flag == 1) {
expListView.setVisibility(8);
// main_error.setText("Internet Connection Error! Please check your network settings and try again");
// main_error.setVisibility(0);
} else {
/*
* navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
* navMenuIcons .getResourceId(0, -1),"1"));
*/
expListView.setVisibility(0);
// main_error.setText("");
// main_error.setVisibility(8);
// Recycle the typed array
navMenuIcons.recycle();
expListView
.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
/*adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);*/
listAdapter=new ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setItemChecked(0, true);
expListView.setSelection(0);
}
}
}
}
Presumably, your Drawer consists of only the ExpandableListView expListView. If you check the AsyncTask's doInBackground() method, you'll see that error_flag is set to 1 if there's no network available. Then, in the onPostExecute() method:
if (error_flag == 1) {
expListView.setVisibility(8);
A value of 8 corresponds to View.GONE, so, essentially, if there is no network, there is no Drawer.

Android ActionBarCompat - Navigation Drawer with multiple fragments

Im new to the ActionBarCompat library.I want to develop an app which contains multiple fragments. Here is what i want to do
1.How to open a fragment when user select that from Navigation Drawer.
2.How to set a startup fragment which displays startup layout (example- In Google plus app,first its displays news feeds.when we select profile item from the side menu,then its hide the side menu/Navigation drawer and displays the profile layout)
Currently i have side menu and one fragment.
Here is the tutorial that i used to follow- wptrafficanalyzer
If you are going to use a slide out menu I recommend you use this slidemenu library I use it in my applications and it allows you to place whatever you want in the slide out menu, the menu is just a frame layout and you can put whatever you want in it (Listview, GridView, or even just a picture)
I am assuming by side menu you meant Navigation Drawer. You can find an answer in the below link.
Navigation Drawer with backword compatibility android
Do read
http://developer.android.com/design/patterns/navigation-drawer.html
Fragment is hosted by a Activity. So you need a container in the activity layout.
<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 // container to which you add or replace fragments
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
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.support.v4.widget.DrawerLayout>
Initially you don't click any item. So initially add fragment1 to the container.
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment1= new Fragment1();
fragTran.add(R.id.content_frame, fragment1);
fragTran.commit();
On click of listitem based on the position
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment3= new Fragment3();
fragTran.replace(R.id.content_frame, fragment3);
fragTran.commit();
Hi check this code
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
DrawerLayout options_drawer;
FrameLayout main_frame;
ListView slider_list;
ActionBar action;
ActionBarDrawerToggle toggler;
BluetoothAdapter blue_adapter;
String options[] = { "Chat", "Device List", "Settings", "Emojis",
"Terms&Conditions" };
Fragment f;
private static final int REQUEST_ENABLE_BT = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// setSupportProgressBarIndeterminateVisibility(true);
action = getSupportActionBar();
action.setHomeButtonEnabled(true);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
options_drawer = (DrawerLayout) findViewById(R.id.drawer);
main_frame = (FrameLayout) findViewById(R.id.main_frame);
slider_list = (ListView) findViewById(R.id.slider_list);
blue_adapter = BluetoothAdapter.getDefaultAdapter();
if (blue_adapter == null) {
Toast.makeText(getApplicationContext(),
"NO BLUETOOTH DEVICE FOUND", Toast.LENGTH_LONG).show();
finish();
}
ArrayAdapter<String> al = new ArrayAdapter<String>(
getApplicationContext(), R.layout.option_text, options);
slider_list.setAdapter(al);
slider_list.setOnItemClickListener(this);
/*
* toggler=new ActionBarDrawerToggle(MainActivity.this,
* options_drawer,R.
* drawable.ic_launcher,R.string.app_name,R.string.app_name){
*
* #Override public void onDrawerOpened(View drawerView) { // TODO
* Auto-generated method stub super.onDrawerOpened(drawerView);
* options_drawer.openDrawer(slider_list); }
*
* };
*/
// options_drawer.setDrawerListener(toggler);
if (savedInstanceState == null) {
f = new chat_fragment();
fragmentTransition(f);
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!blue_adapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
// If the drawer is open, close it; vice versa
if (options_drawer.isDrawerOpen(slider_list)) {
options_drawer.closeDrawer(slider_list);
} else {
options_drawer.openDrawer(slider_list);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
options_drawer.closeDrawer(slider_list);
switch (position) {
case 0:
f = new chat_fragment();
fragmentTransition(f);
break;
case 1:
f = new device_list_fragment();
fragmentTransition(f);
break;
}
}
private void fragmentTransition(Fragment f2) {
// TODO Auto-generated method stub
FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
fx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fx.replace(R.id.main_frame, f2).commit();
}
}
And XML file is
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/slider_list"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff" >
</ListView>
try this link
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
android actionbarcompat is supported library for below android versions.In this you should do some modifications in code.I am giving some sample code with supported library
code:
public class SliderScreen extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
int checkboxValue=0;
// nav drawer title
private CharSequence mDrawerTitle;
private int selectedPosition=0;
private int currentpos=0;
// used to store app title
private CharSequence mTitle;
ProgressDialog progress_dialog;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
public static String letter = "";
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
ActionBarActivity activity;
MDatabase mdatabaseHelper;
String contact_id = "";
Cursor contactsCursor = null, databaseCursor = null,
messageDatabaseCursor = null,imageDatabaseCursor=null;
String contactCursorValue = "0";
int contactCursorRead = 0, messageCursorRead = 0,imageCursorRead=0;
int messageProgressValue = 0, contactProgressValue = 0,imageProgressValue=0;
AlertDialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_screen);
mTitle = mDrawerTitle = getTitle();
// activity=(ActionBarActivity) Context.getApplicationContext();
// 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 = (ListView) findViewById(R.id.list_slidermenu);
progress_dialog = new ProgressDialog(SliderScreen.this);
progress_dialog.setMessage("please wait ");
Builder build=new Builder(SliderScreen.this);
build.setTitle("");
build.setMessage("Do you want to signout ? ");
build.setPositiveButton("Yes",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
build.setNegativeButton("No",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
d=build.create();
// Database retrieval
mdatabaseHelper = new MDatabase(SliderScreen.this, null, null, 1);
mdatabaseHelper.getWritableDatabase();
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), true, 0));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1), true, 0));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true,0));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1), true, getMusicFilesCount()));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1)));
// What's hot, We will add a counter here
// 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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.listbulletes, // nav menu toggle icon
0, // nav drawer open - description for accessibility
0 // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
if(currentpos!=selectedPosition)
{
currentpos=selectedPosition;
displayView(selectedPosition);
}
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// ActivityCompat.invalidateOptionsMenu(getParent());
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(currentpos!=position)
{
Fragment fragment=new DefaultFragment();
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(" ");
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
selectedPosition=position;
mDrawerLayout.closeDrawer(mDrawerList);
/*
// display view for selected nav drawer item
if(selectedPosition==position)
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
displayView(position);
selectedPosition=position;
}
*/}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, 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 ContactsFragment();
break;
case 2:
fragment = new MessagesFragment();
break;
case 3:
fragment = new ImageFragment();
break;
case 4:
fragment = new MusicFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, 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");
}
}
private void showProgressDialog() {
progress_dialog.show();
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().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);
}
}

Categories

Resources