Add forward and back button on a custom toolbar - android

I am trying to add forward and back button on custom toolbar in android studio I have tried adding it as a menu as well as separate buttons but every time when I run the app the buttons are not appearing. Code is working fine I am not able to detect what am i missing here. Here is the code :
XML
<LinearLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/toolbar01"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="0.4"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:src="#drawable/menu"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3">
<Button
android:id="#+id/back"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_back_ios_24">
</Button>
<Button
android:id="#+id/forward"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_forward_ios_24">
</Button>
<Button
android:layout_marginLeft="50dp"
android:id="#+id/refresh"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_refresh_24"
android:layout_marginStart="40dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:progress="50"
android:progressTint="#color/colorPrimary"
android:indeterminate="true"
android:indeterminateDuration="2000"
android:maxHeight="3dp"
android:minHeight="3dp"
tools:targetApi="lollipop" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
>
<WebView
android:id="#+id/webView"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
JAVA:
public class Webview extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private WebView webview;
NavigationView navigationView;
DrawerLayout drawer;
ImageView menuicon, forward, back, refresh;
static final float END_SCALE = 0.7f;
LinearLayout contentView;
ProgressBar progressBar;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
navigationDrawer();
Loadweb();
}
private void toolbuttons() {
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onForwardPressed();
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webview.reload();
}
});
}
private void Loadweb() {
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
}
});
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
progressBar.setMax(100);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
webview.reload();
}
}, 3000);
}
});
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private void navigationDrawer() {
//navigation view
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
menuicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerVisible(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else drawer.openDrawer(GravityCompat.START);
}
});
animateNavigationDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
webview.reload();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerVisible(GravityCompat.START) || webview.canGoBack()) {
drawer.closeDrawer(GravityCompat.START);
webview.goBack();
} else {
super.onBackPressed();
}
}
public void onForwardPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
Toast.makeText(this, "Can't go back", Toast.LENGTH_SHORT).show();
}
}
private void animateNavigationDrawer() {
drawer.setScrimColor(getResources().getColor(R.color.colorPrimary));
//Add any color or remove it to use the default one!
//To make it transparent use Color.Transparent in side setScrimColor();
//drawerLayout.setScrimColor(Color.TRANSPARENT);
drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Scale the View based on current slide offset
final float diffScaledOffset = slideOffset * (1 - END_SCALE);
final float offsetScale = 1 - diffScaledOffset;
contentView.setScaleX(offsetScale);
contentView.setScaleY(offsetScale);
// Translate the View, accounting for the scaled width
final float xOffset = drawerView.getWidth() * slideOffset;
final float xOffsetDiff = contentView.getWidth() * diffScaledOffset / 2;
final float xTranslation = xOffset - xOffsetDiff;
contentView.setTranslationX(xTranslation);
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
} else if (id == R.id.nav_privacy_policy) {
webview.loadUrl("https://www.nationalsavings.com.pk/privacy-policy.php");
} else if (id == R.id.nav_share) {
Intent shareintent = new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT, "https://www.nationalsavings.com.pk/index.php");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent, "Share via"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Related

Navigation Drawer not Working Properly

When i open this activity, drawer is already opened by default. When i try to close the drawer, it doesn't. In short drawer is malfunctioning. I have attached both XML code & JAVA code.
This is XML File Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_home">
<include
android:id="#+id/action_bar"
layout="#layout/actionbar"
/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/navigation"
app:menu="#menu/drawer_menu"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="210dp"
android:src="#drawable/add_to_cart"
android:elevation="6dp"
android:id="#+id/fab_place_order"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabOrder"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="150dp"
android:src="#drawable/ic_account_balance_wallet_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_balance"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabBalance"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="90dp"
android:src="#drawable/ic_exit_to_app_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_logout"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabExit"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:src="#drawable/menu"
android:elevation="6dp"
android:id="#+id/fab_menu"
app:pressedTranslationZ="12dp"
android:backgroundTint="#color/fabMain"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="230dp"
android:layout_marginEnd="80dp"
android:layout_marginRight="70dp"
android:text="Place Order"
android:textColor="#003200"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignLeft="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="170dp"
android:text="Check Balance"
android:textColor="#000032"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="110dp"
android:text="Logout"
android:textColor="#320000"
android:textStyle="bold"
android:visibility="invisible" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
This is JAVA File Code:
public class HomeActivity extends AppCompatActivity {
ConnectionDetector connectionDetector = new ConnectionDetector(this);
DatabaseHelper helper = new DatabaseHelper(this);
Handler handler = new Handler();
FloatingActionButton fab_menu,fab_balance,fab_logout,fab_order;
Animation fabOpen,fabClose,fabClockwise,fabAnticlockwise;
boolean isOpen = false, status = false;
ProgressBar progressBar;
private boolean isUserClickedBackButton = false;
private DrawerLayout drawerLayout;
TextView t1,t2,t3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
helper.startFirebaseDB();
Toolbar toolbar = findViewById(R.id.action_bar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
toggle.syncState();
progressBar = findViewById(R.id.progressBar);
fab_menu = findViewById(R.id.fab_menu);
fab_menu.setEnabled(false);
fab_order = findViewById(R.id.fab_place_order);
fab_balance = findViewById(R.id.fab_balance);
fab_logout = findViewById(R.id.fab_logout);
t1 = findViewById(R.id.label1);
t2 = findViewById(R.id.label2);
t3 = findViewById(R.id.label3);
fabOpen= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_open);
fabClose= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
fabClockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_clockwise);
fabAnticlockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_anticlockwise);
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
fab_menu.setEnabled(true);
}
},2000);
fab_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isOpen)
{
fab_order.startAnimation(fabClose);
fab_balance.startAnimation(fabClose);
fab_logout.startAnimation(fabClose);
fab_menu.startAnimation(fabAnticlockwise);
fab_balance.setClickable(false);
fab_logout.setClickable(false);
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.INVISIBLE);
t2.setVisibility(View.INVISIBLE);
t3.setVisibility(View.INVISIBLE);
}
},200);
isOpen = false;
}
else
{
fab_order.startAnimation(fabOpen);
fab_balance.startAnimation(fabOpen);
fab_logout.startAnimation(fabOpen);
fab_menu.startAnimation(fabClockwise);
fab_balance.setClickable(true);
fab_logout.setClickable(true);
isOpen = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
}
},200);
}
}
});
fab_order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = helper.checkUserStatus(helper.getUser());
if(!connectionDetector.isConnected()) {
Toast.makeText(HomeActivity.this, "Check your internet connection !!!", Toast.LENGTH_LONG).show();
return;
}
else if(!status) {
Toast t1 = Toast.makeText(HomeActivity.this, "Access Denied !!!", Toast.LENGTH_LONG);
Toast t2 = Toast.makeText(HomeActivity.this, "Please contact: Ayaz Handloom Store", Toast.LENGTH_LONG);
t1.setGravity(Gravity.CENTER,0,0);
t1.show();
t2.setGravity(Gravity.CENTER,0,0);
t2.show();
return;
}
else {
Intent newOrder = new Intent(HomeActivity.this, NewOrderActivity.class);
startActivity(newOrder);
finish();
}
}
});
fab_balance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent balance = new Intent(HomeActivity.this,BalanceActivity.class);
startActivity(balance);
finish();
}
});
fab_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.edit_profile:
break;
case R.id.change_password:
break;
case R.id.settings:
break;
case R.id.logout:
DialogInterface.OnClickListener dialogBox = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast cancel = Toast.makeText(HomeActivity.this, "Request cancelled !!!", Toast.LENGTH_SHORT);
cancel.setGravity(Gravity.CENTER,0,0);
cancel.show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setMessage("Are you sure to logout?").setPositiveButton("Yes", dialogBox).setNegativeButton("No", dialogBox).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else {
if (!isUserClickedBackButton) {
Toast.makeText(this, "Press back key again for Main Page !!!", Toast.LENGTH_LONG).show();
isUserClickedBackButton = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
isUserClickedBackButton = false;
}
}, 3000);
} else {
Intent back = new Intent(HomeActivity.this, MainActivity.class);
startActivity(back);
finish();
}
}
}
}
If i delete XML code which is inside DrawerLayout, then it works fine.
you forgot to add drawerLayout.addDrawerListener(toggle); before toggle.syncState();

How to stop swipetorefresh progressbar in webview?

I'm new with Android development. I got trouble using SwipeToRefresh option in WebView. I'm trying to solve it from a mounth now and after trying several codes, it's not working. Also Youtube video is not playing in full screen from the WebView...
Here's my question: How to hide SwipeToRefresh ProgressBar and stop running?
Here is my MainActivity class:
public class WebViewActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private WebView myWebView;
private SwipeRefreshLayout mSwipeRefreshLayout;
//HTML5 video
private View mCustomView;
private int mOriginalSystemUiVisibility;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
setContentView(R.layout.activity_web_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-App Id");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//WebView
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshlayout);
myWebView = (WebView) findViewById(R.id.webview);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebViewSettings();
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
myWebView.loadUrl("http://www.youtube.com");
//force links open in webview only
myWebView.reload(); // refreshes the WebView
}
});
myWebView.setWebViewClient(new MyWebViewClient());
}
#SuppressLint("SetJavaScriptEnabled")
#SuppressWarnings("deprecation")
private void myWebViewSettings() {
// set javascript and zoom and some other settings
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDisplayZoomControls(false);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
// enable all plugins (flash)
myWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
}
#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.web_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Subject more ");
startActivity(Intent.createChooser(shareIntent, "Share Via"));
break;
default:
break;
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.facebook) {
// Handle the camera action
myWebView.loadUrl("http://www.facebook.com");
} else if (id == R.id.google) {
myWebView.loadUrl("http://www.google.com");
}
//share in navigation
else if (id == R.id.share) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Androidwebview");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Try out this cool app www.applink.com");
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
//rate us in navigation
else if (id == R.id.rateus) {
String str = getPackageName();
try
{
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=" + str)));
}
catch (ActivityNotFoundException localActivityNotFoundException)
{
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=" + str)));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// show error if no network
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadUrl("file:///android_asset/error.png");
}
// load from
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
//progress bar
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progress1).setVisibility(View.GONE);
}
}
//goto previous page when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
// This fires when a notification is opened by tapping on it or one is received while the app is running.
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
#Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
try {
if (additionalData != null) {
if (additionalData.has("actionSelected"))
Log.d("OneSignalExample", "OneSignal notification button with id " + additionalData.getString("actionSelected") + " pressed");
Log.d("OneSignalExample", "Full additionalData:\n" + additionalData.toString());
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
Here is XML File:
<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"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_web_view"
android:layout_width="fill_parent"
android:layout_above="#+id/adView"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.androidwebview.WebViewActivity"
tools:showIn="#layout/app_bar_web_view">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"
android:layout_above="#+id/adView"
android:visible="false"
android:layout_alignParentLeft="true" />``
</android.support.v4.widget.SwipeRefreshLayout>
<FrameLayout
android:id="#+id/customViewContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"/>
<ProgressBar
android:id="#+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="80dp"
android:layout_height="80dp" />
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
I had the same problem and i found the question in another thread:
final SwipeRefreshLayout swipeLayout =
(SwipeRefreshLayout)this.findViewById(R.id.swipeToRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebView.reload(); // refreshes the WebView
if (null != swipeLayout) {
swipeLayout.setRefreshing(false);
}
}
});

Navigation drawer implementation with activities using inheritance

In my app I have to use navigation drawer with all activities. So I have created a base activity called DrawerActivity. I wrote the code for navigation drawer in DrawerActivity and then extended the UserDashBoardActivity from DrawerActivity.
The problem is that DrawerActivity properties aren't executed in UserDashBoardActivity. I can't interact with DrawerActivity in UserDashBoardActivity. Here that drawer menu is in ActionBar in all the activities.
This is my DrawerActivity
public class DrawerActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerItems = getResources().getStringArray(R.array.navigation_drawer_items_array);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(
this, R.layout.drawer_list_items, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View view) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
for (int index = 0; index < menu.size(); index++) {
MenuItem menuItem = menu.getItem(index);
if (menuItem != null) {
// hide the menu items if the drawer is open
menuItem.setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(DrawerActivity.this, UserDashBoardActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(DrawerActivity.this, AdmissionActivity.class);
startActivity(intent);
break;
}
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
This is my UseDashBoardActivity
public class UserDashBoardActivity extends DrawerActivity {
private Context context;
private ImageButton searchBtn;
private ImageButton favBtn;
private ImageButton profileBtn;
private ImageButton reminderBtn;
private ImageButton logoutBtn;
private ImageButton notificationBtn;
private ImageView seatchIcon;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onResume();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#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_user_dash_boad, menu);
return true;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notify:
return true;
case R.id.action_favourite:
return true;
case R.id.action_navigation:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setCustomView(R.layout.action_bar_layout);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
searchBtn = (ImageButton) findViewById(R.id.search_btn);
favBtn = (ImageButton) findViewById(R.id.fav_btn);
profileBtn = (ImageButton) findViewById(R.id.profile_btn);
reminderBtn = (ImageButton) findViewById(R.id.reminder_btn);
notificationBtn = (ImageButton) findViewById(R.id.notification_btn);
logoutBtn = (ImageButton) findViewById((R.id.logout_btn));
final EditText Search = (EditText)findViewById(R.id.emailAddress);
mDrawerList = (ListView)findViewById(R.id.drawer_layout);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent regAct = new Intent(getApplicationContext(), SearchActivity.class);
// Clears History of Activity
regAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(regAct);
}
});
favBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
Intent tabAct = new Intent(getApplicationContext(),TabHostActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
profileBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent tabAct = new Intent(getApplicationContext(),AboutCollegeActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
}
}
This is my actionbar xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appmunu="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.after2.svirtzone.after2_gradle.UserDashBoardActivity">
<item
android:id="#+id/action_notify"
android:icon="#drawable/mail_icon"
appmunu:showAsAction="always"
android:title="Notification" />
<item
android:id="#+id/action_favourite"
android:icon="#drawable/favourite_icon"
appmunu:showAsAction="always"
android:title="Favourite" />
<item
//this is the menu button for navigation drawer
android:id ="#+id/action_navigation"
android:icon="#drawable/ic_menu"
appmunu:showAsAction = "always"
android:title="navigation"
android:layout_gravity="left"/>
</menu>
This is the xml layout for navigationdrawer listview
<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/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_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:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
This layout is UserDashboard layout
?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_gravity="center"
android:background="#color/appblue"
android:orientation="vertical">
<EditText
android:id="#+id/emailAddress"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#drawable/edit_text_style"
android:gravity="center|start"
android:hint="#string/edittext_hint"
android:inputType="textEmailAddress"
android:maxLength="40"
android:textSize="18sp"
android:visibility="gone" />
<ImageView
android:id="#+id/search_icon_btn"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="580dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-90dp"
android:padding="5dp"
android:src="#drawable/search_icon" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginRight="210dp"
android:layout_marginTop="30dp"
android:background="#drawable/search_blue"
android:gravity="center" />
<TextView
android:id="#+id/searchCollege"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="100dp"
android:layout_marginTop="20dp"
android:text="#string/search_college"
android:textColor="#color/green"
android:textSize="30sp" />
<ImageButton
android:id="#+id/fav_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="200dp"
android:layout_marginRight="5dp"
android:layout_marginTop="-305dp"
android:background="#drawable/fav_blue"
android:gravity="center" />
<TextView
android:id="#+id/myFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="500dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:text="#string/my_favourites"
android:textColor="#color/green"
android:textSize="30sp" />
</LinearLayout>
The UserDashboard activity is executed as it is but I need the property of DrawerActivity to be executed along with this activity. How to do it?
Let the parent Activity add the required ViewGroup as child of the FrameLayout. To achieve this, use the following method for DrawerActivity:
protected void addToContentView(int layoutResID)
{
// as part of onCreate() we had already
// setContentView(R.layout.activity_drawer);
if (layoutResID >= 0)
{
Toast.makeText(this, "activity content found", Toast.LENGTH_LONG).show();
FrameLayout fl = (FrameLayout)findViewById(R.id.activity_frame);
View.inflate(this, layoutResID, fl);
}
else
{
Toast.makeText(this, "activity content missing", Toast.LENGTH_LONG).show();
}
}
Then, in the onCreate() method of the child Activity:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// call this instead of setContentView()
addToContentView(R.layout.activity_user_dashboard);
// put here your code as before...
}
Drawer's layout:
<?xml version="1.0" encoding="utf-8"?>
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<!--you need to add everything to this frameLayout then only you will be able to access Navigation DrawerLayout-->
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/navigation_list"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:background="#color/white"
/>
</android.support.v4.widget.DrawerLayout>
The Activity with Drawer:(Only important code is shown)
public abstract class BaseDrawerLayoutActivity extends AppCompatActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout_activity);
//rest of the things
//NOTE: loadNavMenu is abstract so that you can implement it in other activities as per you need, otherwise remove this and load it here itself
loadNavMenu();
}
protected abstract void loadNavMenu();
// call this method whenever you enter new activity and load the fragment here.
public void showFragment(Fragment object, String title) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, object);
transaction.commit();
}}
Those activities which need the drawer menu can inherit above class. Not inflate all the layout's inside FrameLayout only.
public class MainActivity extends BaseDrawerLayoutActivity {
public static final String TAG = OLMSActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the method below will call the BaseDrawerLayoutActivity method and change the fragment for you to see.
showFragment(new MyProfileFragment(), "My Profile");
}
#Override
protected void loadNavMenu() {
NavItems.clear();
//load your menu items
}
private void loadNavFavourites(){
//todo
}}
MyProfileFragment is just a class with fragment and this one call inflate a layout in its OnCreateView method.

navigation drawer doesn't opened

In my app i am extending the drawerActivity which is having the properties of navigation drawer. The problem is that menu icon appears at the action bar. When i click the action bar nothing happends. Here i have posted the ode for your reference
drawerActivity.class
public class DrawerActivity extends ActionBarActivity {
protected DrawerLayout mDrawerLayout = null;
protected ListView mDrawerList = null;
protected String[] mDrawerItems;
protected ActionBarDrawerToggle mDrawerToggle = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerItems = getResources().getStringArray(R.array.navigation_drawer_items_array);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(
this, R.layout.drawer_list_items, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View view) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
for (int index = 0; index < menu.size(); index++) {
MenuItem menuItem = menu.getItem(index);
if (menuItem != null) {
// hide the menu items if the drawer is open
menuItem.setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(DrawerActivity.this, UserDashBoardActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(DrawerActivity.this, AdmissionActivity.class);
startActivity(intent);
break;
}
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
This is userDashBoardActivity
public class UserDashBoardActivity extends DrawerActivity {
private Context context;
private ImageButton searchBtn;
private ImageButton favBtn;
private ImageButton profileBtn;
private ImageButton reminderBtn;
private ImageButton logoutBtn;
private ImageButton notificationBtn;
private ImageView seatchIcon;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onResume();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#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_user_dash_boad, menu);
return true;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notify:
return true;
case R.id.action_favourite:
return true;
case R.id.action_navigation:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
searchBtn = (ImageButton) findViewById(R.id.search_btn);
favBtn = (ImageButton) findViewById(R.id.fav_btn);
profileBtn = (ImageButton) findViewById(R.id.profile_btn);
reminderBtn = (ImageButton) findViewById(R.id.reminder_btn);
notificationBtn = (ImageButton) findViewById(R.id.notification_btn);
logoutBtn = (ImageButton) findViewById((R.id.logout_btn));
final EditText Search = (EditText)findViewById(R.id.emailAddress);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent regAct = new Intent(getApplicationContext(), SearchActivity.class);
// Clears History of Activity
regAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(regAct);
}
});
favBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
Intent tabAct = new Intent(getApplicationContext(),TabHostActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
profileBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent tabAct = new Intent(getApplicationContext(),AboutCollegeActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
}
}
This Activity is extends from DrawerActivity
This is my Drawer.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/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_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:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
this is UserDashBoard.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_gravity="center"
android:background="#color/appblue"
android:orientation="vertical">
<EditText
android:id="#+id/emailAddress"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:background="#drawable/edit_text_style"
android:gravity="center|start"
android:hint="#string/edittext_hint"
android:inputType="textEmailAddress"
android:maxLength="40"
android:textSize="18sp"
android:visibility="gone" />
<ImageView
android:id="#+id/search_icon_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="350dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-60dp"
android:padding="5dp"
android:src="#drawable/search_icon" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="100dp"
android:layout_marginTop="15dp"
android:background="#drawable/search_blue"
android:gravity="center" />
<TextView
android:id="#+id/searchCollege"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginRight="100dp"
android:layout_marginTop="10dp"
android:text="#string/search_college"
android:textColor="#color/green"
android:textSize="18sp" />
<ImageButton
android:id="#+id/fav_btn"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="100dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-150dp"
android:background="#drawable/fav_blue"
android:gravity="center" />
<TextView
android:id="#+id/myFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="650px"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="#string/my_favourites"
android:textColor="#color/green"
android:textSize="18sp" />
<ImageButton
android:id="#+id/profile_btn"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="100dp"
android:layout_marginTop="10dp"
android:background="#drawable/profile_blue"
android:gravity="center" />
</LinearLayout>
The Adapter that you are setting is wrong you are using an ArrayAdapter but you should be actually using an ActionBarDrawerToggle like this
private void initDrawer() {
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
if you need furthur assistance refer this link http://developer.android.com/training/implementing-navigation/nav-drawer.html
You need to add listview in navigation drawer like below.
<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/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
 android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start" >
<ListView android:id="#+id/left_drawer"
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.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
In your drawer activity (DrawerActivity.class)
public class DrawerActivity extends ActionBarActivity
Replace the actionbaractivity with appcompactability. I think this should solve your problem.

navigation drawer not opening for webview button click

I am trying to open a nav drawer when user clicks on a webview (HTML) button. I have a code which works fine when I use Android button but it does not work when I use HTML button. The navigation drawer shows when you drag it from left side but not when you click the HTML button.
activity_main
<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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light"
android:orientation="vertical" >
<!-- <Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="open"
android:text="Button" /> -->
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/background_light"
android:orientation="vertical"
android:padding="5dp" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.webviewnav.MyListFragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
MyListFragment1
public class MyListFragment1 extends ListFragment {
String[] month = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListAdapter myListAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, month);
setListAdapter(myListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfragment1, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
}
MainActivity
public class MainActivity extends Activity {
private DrawerLayout drawerLayout;
private View drawerView;
WebView wv;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerView = (View)findViewById(R.id.drawer);
/*Button buttonOpenDrawer = (Button)findViewById(R.id.opendrawer);
buttonOpenDrawer.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
drawerLayout.openDrawer(drawerView);
}
}); */
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(new WebAppInterface(this), "Luke");
wv.loadUrl("file:///android_asset/www/mind.html");
drawerLayout.setDrawerListener(myDrawerListener);
} //onCreate ends
DrawerListener myDrawerListener = new DrawerListener(){
#Override
public void onDrawerClosed(View drawerView) {
//textPrompt.setText("onDrawerClosed");
}
#Override
public void onDrawerOpened(View drawerView) {
//textPrompt.setText("onDrawerOpened");
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
//textPrompt.setText("onDrawerSlide: " + String.format("%.2f", slideOffset));
}
#Override
public void onDrawerStateChanged(int newState) {
String state;
switch(newState){
case DrawerLayout.STATE_IDLE:
state = "STATE_IDLE";
break;
case DrawerLayout.STATE_DRAGGING:
state = "STATE_DRAGGING";
break;
case DrawerLayout.STATE_SETTLING:
state = "STATE_SETTLING";
break;
default:
state = "unknown!";
}
//textPrompt2.setText(state);
}};
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showDialog() {
drawerLayout.openDrawer(drawerView);
//Toast.makeText(getApplicationContext(), "Good", Toast.LENGTH_SHORT).show();
}
}
/*public void open(View v){
drawerLayout.openDrawer(drawerView);
} */
} //Activity ends
Does showDialog method get called? If it is so, try to call drawerLayout.openDrawer from UI thread: MainActivity.this.runOnUiThread(...)

Categories

Resources