I have done everything, I can see the navigation drawer but my app is crashing. Can anyone explain whats the problem in the below code. Now whenever I try to open ForumActivty it is crashing.
public class ForumActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://discuss.flarum.org/";
String webURL, webTitle ;
private DrawerLayout mDrawerLayout;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomApplication)getApplication()).checkUserLogin();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_forum);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Bundle bundle = getIntent().getExtras();
if(bundle != null){
fragment = new ProfileFragment();
}else{
fragment = new TopicFragment();
}
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_content, fragment).commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_topic) {
fragment = new TopicFragment();
}
else if(id == R.id.nav_profile){
fragment = new ProfileFragment();
}
else if(id == R.id.nav_scores){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_share){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_contact){
startActivity(new Intent(ForumActivity.this, ContactActivity.class));
}
else if(id == R.id.nav_settings){
fragment = new SettingsFragment();
}
else if(id == R.id.nav_logout){
((CustomApplication)getApplication()).getShared().setUserData("");
Intent logoutIntent = new Intent(ForumActivity.this, LoginActivity.class);
logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(logoutIntent);
finish();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_content, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(ForumActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
webURL = webView.getUrl();
webTitle = webView.getTitle();
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
I know I am doing something wrong above but I have included everything in layout. It would be really nice if someone can help
You should have also shared the code of layout&activity which already has a Navigation Drawer. Anyway, you can follow this guide.
For you layout file, you will need to put your CoordinatorLayout inside DrawerLayout like this and add a NavigationView (check the xml layout of other Activity which already has a navigation drawer and copy <android.support.design.widget.NavigationView> and replace with the one in below example):
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<im.delight.android.webview.AdvancedWebView
android:id="#+id/newWeb"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
></im.delight.android.webview.AdvancedWebView>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loader"
android:layout_weight="1"
android:layout_gravity="center_vertical|center_horizontal|center"/>
</android.support.design.widget.CoordinatorLayout>
<!-- Replace this with the one in other activity layout -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
After that there will be some code that you will need to add in your Activity class. You can check the link I put above and after reading it you can understand which code you need to copy from other Activity which already has a navigation drawer.
Related
I can't display videos in full screen mode using webview app.
I tried some solutions found on StackOverflow but the issue still the same, in my case I can't see the full screen button when running videos in my website in WebView. I already have in my manifest:
android:allowBackup="true"
android:hardwareAccelerated="true"
This is my activity Java file
public boolean doubleBackToExitPressedOnce = false;
private InterstitialAd interstitial;
private NavigationView navigationView;
public Timer AdTimer;
private boolean open_from_push = false;
public static final String PROPERTY_REG_ID = "notifyId";
private static final String PROPERTY_APP_VERSION = "appVersion";
SharedPreferences preferences;
String reg_cgm_id;
static final String TAG = "MainActivity";
private boolean first_fragment = false;
private double latitude;
private double longitude;
private VideoEnabledWebView webView;
private VideoEnabledWebChromeClient webChromeClient;
#Override
protected void onPause() {
super.onPause();
if (AdTimer != null) {
AdTimer.cancel();
AdTimer = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.share_button:
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
String sAux = getString(R.string.share_text) + "\n";
sAux = sAux + getString(R.string.share_link) + "\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) { //e.toString();
}
return true;
case R.id.btn11:
android.os.Process.killProcess(android.os.Process.myPid());
finish();
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (getString(R.string.rtl_version).equals("true")) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
// Go to first fragment
Intent intent = getIntent();
if (intent.getExtras() != null && intent.getExtras().getString("link", null) != null && !intent.getExtras().getString("link", null).equals("")) {
open_from_push = true;
String url = null;
if (intent.getExtras().getString("link").contains("http")) {
url = intent.getExtras().getString("link");
} else {
url = "http://" + intent.getExtras().getString("link");
}
Bundle bundle = new Bundle();
bundle.putString("type", "url");
bundle.putString("url", url);
Fragment fragment = new FragmentWebInteractive();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "FragmentWebInteractive").commit();
first_fragment = true;
} else if (savedInstanceState == null) {
Bundle bundle = new Bundle();
bundle.putString("type", getString(R.string.home_type));
bundle.putString("url", getString(R.string.home_url));
Fragment fragment = new FragmentWebInteractive();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "FragmentWebInteractive").commit();
first_fragment = true;
}
// ------------------------------- AdMob Banner ------------------------------------------------------------
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
// -------------------------------- AdMob Interstitial ----------------------------
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
// Load ads into Interstitial Ads
interstitial.loadAd(adRequest);
AdTimer = new Timer();
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function with timer
if (AdTimer != null) {
AdTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
displayInterstitial();
}
});
}
}, Integer.parseInt(getString(R.string.admob_interstiial_delay)));
}
}
});
if (preferences.getBoolean("pref_geolocation_update", true)) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// create class object
GPSTracker gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
int appVersion = getAppVersion(this);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("latitude", "" + latitude);
editor.putString("longitude", "" + longitude);
editor.putString(PROPERTY_APP_VERSION, ""+appVersion);
editor.commit();
Log.d("GPS", "Latitude: " + latitude + ", Longitude: " + longitude);
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
if (preferences.getBoolean("pref_gps_remember", false)) {
gps.showSettingsAlert();
}
}
} else {
// Request permission to the user
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1
);
}
}
And this is the XML
<RelativeLayout 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/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true" />
</android.support.v4.widget.SwipeRefreshLayout>
Can someone tell me what can I do to solve this?
Note that I have embedded iFrame videos on my Wordpress website.
You need to implement showCustomView & hideCustomView method of WebChromeClient, also You need android:hardwareAccelerated="true" in your AndroidManifest File.
Here one exemple from stackoverflow user.
Resource Link
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_gravity="center"
/>
<FrameLayout
android:id="#+id/customViewContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
/>
</LinearLayout>
video_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/progress_indicator"
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar android:id="#android:id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:paddingTop="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="loading"
android:textSize="14sp"
android:textColor="?android:attr/textColorPrimary"/>
</LinearLayout>
MyActivity.java
package com.example.webview;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class MyActivity extends Activity {
private WebView webView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private myWebChromeClient mWebChromeClient;
private myWebViewClient mWebViewClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http://m.youtube.com");
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
webView.onPause();
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
webView.onResume();
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
if (inCustomView()) {
hideCustomView();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
class myWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
}
return mVideoProgressView;
}
#Override
public void onHideCustomView() {
super.onHideCustomView(); //To change body of overridden methods use File | Settings | File Templates.
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
}
}
Disclaimer: This is the first app I am building so I am learning the hard way to use fragments first, so my code is all over the place.
I have menu items inside a navigation view that loads fine however the menu item clicks don't work. It doesn't crash it just stares at me. I would like to use an intent to display a fragment and I am lost from changing and trying so many different options.
XML FOR NAV DRAWER & MENU ITEMS:
<android.support.v4.widget.DrawerLayout
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:id="#+id/activity_pageone"
android:background="#drawable/rygg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarThumbVertical="#color/primary_dark_color"
tools:openDrawer="start"
tools:context="com.android.nohiccupsbeta.pageone">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.NavigationView
android:id="#+id/navigation_header_container"
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:itemIconTint="#color/category_vodka"
app:itemTextColor="#color/primary_dark_color"
app:menu="#menu/drawermenu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
JAVA:
public class pageone extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pageone);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawermenu, menu);
return true;
}
/**
*
* #param item For the hamburger button
* #return
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.itemWhiskey:
Intent whiskeyIntent = new Intent(pageone.this, whiskeyActivity.class);
startActivity(whiskeyIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Make sure the drawer open and closes in sync with UI visual
* #param savedInstanceState
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
/**
* Function to make sure all the drawer open & closes properly
*/
public void setupDrawer() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
#Override
public void onDrawerClosed(View closeView) {
Toast.makeText(pageone.this, "Happy You Learned", Toast.LENGTH_SHORT).show();
super.onDrawerClosed(closeView);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View openView) {
Toast.makeText(pageone.this, "Effects Of Alcohol", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(openView);
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(mToggle);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
XML FOR FRAGMENT:
<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"
android:orientation="vertical"
android:id="#+id/frame_container2"
tools:context="com.android.nohiccupsbeta.WhiskeyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/frag_whiskey_skin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:textColor="#000000"
android:textSize="16sp" />
<ImageButton
android:id="#+id/expand_collapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:background="#android:color/transparent"
android:src="#drawable/ic_expand_more"
android:padding="16dp"/>
</FrameLayout>
JAVA:
public class WhiskeyFragment extends Fragment {
private TextView mWhiskeySkin;
#Override
public void onViewCreated(View view, #Nullable Bundle SavedInstanceState) {
super.onViewCreated(view, SavedInstanceState);
getActivity().setTitle("WHISKEY EFFECTS");
mWhiskeySkin = (TextView) view.findViewById(R.id.frag_whiskey_skin);
mWhiskeySkin.setText(R.string.whiskey_skin);
hasOptionsMenu();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_whiskey, container, false);
hasOptionsMenu();
return v;
}
}
XML FOR SECOND ACTIVITY:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
public class whiskeyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whiskey);
}
public class Whiskeyed {
private String whiskeySkin;
private String whiskeyBrain;
public String getWhiskeySkin(){
return whiskeySkin;
}
public String getWhikeyBrain(){
return whiskeyBrain;
}
public void setWhiskeySkin(String whiskey_skin){
this.whiskeySkin = whiskey_skin;
}
public void setWhiskeyBrain(String whiskeyBrain) {
this.whiskeyBrain = whiskeyBrain;
}
}
}
try to change to content of your onNavigationItemSelected of your pageone.java
from here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
to here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone); // ID of your drawerLayout
int id = item.getItemId();
switch (id) {
case R.id.menu1: // Change this as your menuitem in menu.xml.
// Your fragment code goes here..
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
break;
case R.id.menu2: // Change this as your menuitem in menu.xml.
// or Your fragment code goes here...
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START, true);
return true;
}
I am trying to retrieve data from server and display it in listview. But when I compile this it is not working and the list is even not showing in the activity.
Mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/fab_margin"
android:orientation="vertical" >
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/edItem"
android:layout_width="180dp"
android:layout_marginTop="10dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:orientation="horizontal">
<TextView
android:id="#+id/edUnit"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edPrice"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edDisc"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</AbsoluteLayout>
</LinearLayout>
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.user.merchant.MainActivity"
tools:showIn="#layout/app_bar_main">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:dividerHeight="10dp">
</ListView>
<SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</SearchView>
</RelativeLayout>
AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
// private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
CustomFilter filter;
private LayoutInflater inflater;
private List<InventoryModel> InventoryModelItems;
private List<InventoryModel> filterList;
public CustomListAdapter(Activity activity, List<InventoryModel> InventoryModelItems) {
this.activity = activity;
this.InventoryModelItems = InventoryModelItems;
this.filterList=InventoryModelItems;
}
#Override
public int getCount() {
return InventoryModelItems.size();
}
#Override
public Object getItem(int location) {
return InventoryModelItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.mylist, null);
TextView ItemName = (TextView) convertView.findViewById(R.id.edItem);
TextView Unit = (TextView) convertView.findViewById(R.id.edUnit);
TextView Price = (TextView) convertView.findViewById(R.id.edPrice);
TextView Discount = (TextView) convertView.findViewById(R.id.edDisc);
// getting InventoryModel data for the row
InventoryModel m = InventoryModelItems.get(position);
// thumbnail image
// title
ItemName.setText(m.getItemName());
// rating
Unit.setText("Unit: " + (m.getUnit()));
// release year
Price.setText("Rs: " + String.valueOf(m.getPrice()));
Discount.setText("Discount: " + String.valueOf(m.getUnit()));
return convertView;
}
#Override
public Filter getFilter() {
if(filter==null)
{
filter=new CustomFilter();
}
return filter;
}
class CustomFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint != null&&constraint.length()>0)
{
constraint=constraint.toString().toUpperCase();
ArrayList<InventoryModel> filters=new ArrayList<InventoryModel>();
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getItemName().toUpperCase().contains(constraint))
{
InventoryModel p= new InventoryModel(filterList.get(i).getItemName(),filterList.get(i).getUnit(),filterList.get(i).getPrice(),filterList.get(i).getDiscount());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}
else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
InventoryModelItems=(List<InventoryModel>) results.values;
notifyDataSetChanged();
}
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "url";
private ProgressDialog pDialog;
private List<InventoryModel> InventoryModelList = new ArrayList<InventoryModel>();
private ListView listView;
private CustomListAdapter adapter;
public TextView test;
SearchView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, InventoryModelList);
listView.setAdapter(adapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setLogo(R.drawable.ic_menu_slideshow);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_slideshow));
// test=(TextView)findViewById(R.id.listtest);
setSupportActionBar(toolbar);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
assert getSupportActionBar() != null;
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest InventoryModelReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// test.setText(response);
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
InventoryModel InventoryModel = new InventoryModel();
InventoryModel.setItemName(obj.getString("Item_Name"));
InventoryModel.setUnit(obj.getString("Unit"));
InventoryModel.setPrice(((Number) obj.get("Price"))
.floatValue());
InventoryModel.setDiscount(((Number) obj.get("Discount")).floatValue());
// adding InventoryModel to InventoryModels array
InventoryModelList.add(InventoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(InventoryModelReq);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intenthome = new Intent(MainActivity.this, MainActivity.class);
startActivity(intenthome);
}
});*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentfloat = new Intent(MainActivity.this, ItemAdd.class);
startActivity(intentfloat);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//toggle.setHomeAsUpIndicator(R.drawable.ic_menu_slideshow);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.account) {
Intent intentaccount = new Intent(MainActivity.this, account.class);
startActivity(intentaccount);
}
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.action_notify) {
Intent intentNotify = new Intent(MainActivity.this, Notification.class);
startActivity(intentNotify);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_processing) {
// Handle the camera action
Intent intentProcessing = new Intent(MainActivity.this, ProcessingItem.class);
startActivity(intentProcessing);
} else if (id == R.id.nav_processed) {
Intent intentProcessed = new Intent(MainActivity.this, ProcessedItem.class);
startActivity(intentProcessed);
} else if (id == R.id.nav_Aborted) {
Intent intentAborted = new Intent(MainActivity.this, AbortedIem.class);
startActivity(intentAborted);
} else if (id == R.id.nav_delivery) {
Intent intentDelivered = new Intent(MainActivity.this, DeliveredItem.class);
startActivity(intentDelivered);
}
else if (id == R.id.logout)
{
// private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivityMerchant.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I'm trying to create an activity with three different fragments as menus.
The user should see only the fragment he needs to according to some data the activity has.
This is my main XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/MainScreenLayout"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="ibuy.ibuy.MainScreen">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ibuy.ibuy.MainScreen">
.
.
.
<fragment
android:id="#+id/navigation_drawer1"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="Menus.ManagerMainMenu"
tools:layout="#layout/fragment_navigation_drawer"
android:alpha="255"/>
<fragment
android:id="#+id/navigation_drawer2"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="Menus.MainConnectedMenu"
tools:layout="#layout/fragment_navigation_drawer"
android:alpha="255"/>
<fragment
android:id="#+id/navigation_drawer3"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="Menus.MainDisConnectedMenu"
tools:layout="#layout/fragment_navigation_drawer"
android:alpha="255"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
This is my main Java file:
public class MainScreen extends ActionBarActivity implements ManagerMainMenu.NavigationDrawerCallbacks,MainConnectedMenu.NavigationDrawerCallbacks,MainDisConnectedMenu.NavigationDrawerCallbacks {
.
.
.
private ManagerMainMenu mnMenu = new ManagerMainMenu();
private MainConnectedMenu conMenu = new MainConnectedMenu();
private MainDisConnectedMenu disMenu = new MainDisConnectedMenu();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Bundle extras = getIntent().getExtras();
.
.
.
mnMenu = (ManagerMainMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer1);
mnMenu.setUp(R.id.navigation_drawer1, (DrawerLayout) findViewById(R.id.drawer_layout));
conMenu = (MainConnectedMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer2);
conMenu.setUp(R.id.navigation_drawer2, (DrawerLayout) findViewById(R.id.drawer_layout));
disMenu = (MainDisConnectedMenu) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer3);
disMenu.setUp(R.id.navigation_drawer3, (DrawerLayout) findViewById(R.id.drawer_layout));
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (storeID > 0) {
ft.show(mnMenu);
ft.hide(conMenu);
ft.hide(disMenu);
} else if (userID > 0) {
ft.hide(mnMenu);
ft.show(conMenu);
ft.hide(disMenu);
} else {
ft.hide(mnMenu);
ft.hide(conMenu);
ft.show(disMenu);
}
ft.commit();
}
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.MainScreenLayout, new PlaceholderFragment()).commit();
.
.
.
}
.
.
.
}
The three fragments are the same part of their array of list of items.
This is one on the fragments Java file:
public class ManagerMainMenu extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public ManagerMainMenu() { }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{"Store Rank", "Store Details", "Sales", "Add Item",
"Update Store Details", "Personal Details", "LogOut"}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
I tried using setMenuVisibility() and setUserVisibleHint() but it had no influence. Afterwards I tried using FragmentTransaction with show and hide and it also did nothing.
How can I hide two of the fragments and display the third?
thank you in advance!
I think this will solve your problem.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (storeID > 0) {
ft.show(mnMenu);
ft.hide(conMenu);
ft.hide(disMenu);
} else if (userID > 0) {
...
}
And so on..
I have code like this:
DrawerLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/drawerList"
android:layout_width="180dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="1dp"
android:entries="#array/Functions" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
DrawerActivity:
public class Drawer extends Activity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle mDrawerToggle;
private Intent intent;
public RelativeLayout fullLayout;
public FrameLayout frameLayout;
#Override
public void setContentView(int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.content_frame);
drawerLayout = (DrawerLayout) fullLayout.findViewById(R.id.drawerLayout);
drawerList = (ListView) fullLayout.findViewById(R.id.drawerList);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.Functions)));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {}
public void onDrawerOpened(View drawerView){}
};
drawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setIcon(R.drawable.ic_drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(int position) {
drawerLayout.closeDrawers();
switch (position) {
case 0:
intent = new Intent(this, 0Act.class);
startActivity(intent);
break;
case 1:
// intent = new Intent(this, 1Act.class);
break;
case 2:
intent = new Intent(this, 2Act.class);
startActivity(intent);
break;
case 3:
intent = new Intent(this, 3Act.class);
startActivity(intent);
break;
case 4:
// intent = new Intent(this, 4Act.class);
break;
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
FirstActivity:
public class 0Act extends Drawer implements ActionBar.TabListener {
ActionBar.Tab t1,t2,t3;
ActionBar actionBar;
Button oneButton;
final CharSequence[] items = {"1", "2", "3", "4"};
AlertDialog.Builder ad;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.0Act);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
t1 = actionBar.newTab().setText("1");
t2 = actionBar.newTab().setText("2");
t3 = actionBar.newTab().setText("3");
t1.setTabListener(this);
t2.setTabListener(this);
t3.setTabListener(this);
actionBar.addTab(t1);
actionBar.addTab(t2);
actionBar.addTab(t3);
actionBar.setSelectedNavigationItem(0);
oneButton= (Button) this.findViewById(R.id.oneButton);
oneButton.setOnClickListener(new View.OnClickListener(){#Override public void onClick(View v) {ad.show();}});
ad = new AlertDialog.Builder(getActivity());
ad.setTitle("Menu");
ad.setItems(items, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int item) {}});
}
}
I see the drawer - I can click on the drawer but I cannot click on any buttons from the first activity. What is going wrong?
Before added drawer to many activities all working good but now I dont see any error and activity dont working.
Mention super.onClick(v); inside onClick method for your Item1Activity Class