Android: why buttons event not working after press back button? - android

I have defined four buttons that onclick event shows a content, now after click when press
back button that shows same four buttons but click event not working.
I defined a field that if user saw content isLooked=true so when clicked on back button I setContentView(R.layout.index) and I will not allow to exit of current activity.
why not working events after click on back button?
private boolean isLooked = false;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.index);
initialEvents();
} catch (Exception e) {
new com.example.csharp.Log.Error().Save(e);
}
}
private void initialEvents() {
View v = findViewById(R.id.btnChapter1);
v.setOnClickListener(this);
v = findViewById(R.id.btnChapter2);
v.setOnClickListener(this);
v = findViewById(R.id.btnChapter3);
v.setOnClickListener(this);
v = findViewById(R.id.btnChapter4);
v.setOnClickListener(this);
}
#Override
public void onBackPressed() {
if (isLooked) {
setContentView(R.layout.index);
isLooked = false;
} else {
super.onBackPressed();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && isLooked) {
setContentView(R.layout.index);
isLooked = false;
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChapter1:
setContentView(R.layout.chapter1_index);
isLooked = true;
break;
case R.id.btnChapter2:
setContentView(R.layout.chapter2_index);
isLooked = true;
break;
case R.id.btnChapter3:
setContentView(R.layout.chapter3_index);
isLooked = true;
break;
case R.id.btnChapter4:
setContentView(R.layout.chapter4_index);
isLooked = true;
break;
}
}

You are setting new content view when back pressed, this is create a new instance of objects for the layout set. But your on click listener is set for the view set in onCreate.
If you really want to set content on back pressed, then you have to findViewById again and set the listener.

Related

Current menu item view is always null in navigation view

I'm using navigation view. And for some reason i can't get the view of menu item. It's always null. I tried viewobserver, findViewByid, but it didn't work. I need to get y coord of current menu item location while performing item selection event. Is this possible?
initializing drawer
activity.drawerIndicator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (activity.drawerLayout.isDrawerVisible(GravityCompat.START)) {
activity.drawerLayout.closeDrawer(GravityCompat.START);
} else {
activity.drawerLayout.openDrawer(GravityCompat.START);
}
}
});
activity.drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View view, float v) {
}
#Override
public void onDrawerOpened(View view) {
activity.closeKeyboard();
}
#Override
public void onDrawerClosed(View view) {
// your refresh code can be called from here
//activity.closeKeyboard();
}
#Override
public void onDrawerStateChanged(int i) {
}
});
initializing navigation view
public void initNavigationView() {
activity.navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Closing drawer on item click
final int itemId=menuItem.getItemId();
final ViewTreeObserver viewTreeObserver =activity.navigationView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
View menuButton = activity.findViewById(itemId);
// This could be called when the button is not there yet, so we must test for null
if (menuButton != null) {
// Found it! Do what you need with the button
int[] location = new int[2];
menuButton.getLocationInWindow(location);
SharedPreferencesController.getInstance(activity.getApplicationContext()).setTopPosition(location[1]);
// Now you can get rid of this listener
viewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
});
activity.drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.checkin:
if (!menuItem.isChecked())
menuItem.setChecked(true);
return goToCheckinItemMenu();
case R.id.boarding_passes:
return goToBoardingPassesItemMenu(menuItem);
case R.id.flight_status:
return goToFlightStatusItemMenu(menuItem);
case R.id.timetable:
return goToTimetableItemMenu(menuItem);
case R.id.promotion:
return goToPromotionItemMenu(menuItem);
//case R.id.reccomend_app:
// return goToReccomendAppItemMenu();
case R.id.about_app:
return goToAboutAppItemMenu(menuItem);
case R.id.contact_us:
return goToContactUsItemMenu(menuItem);
case R.id.settings:
return goToSettingsItemMenu(menuItem);
case R.id.data_protection:
return goToDataProtectionItemMenu(menuItem);
case R.id.checkin_info:
return goToCheckinInfoItemMenu(menuItem);
case R.id.panorama:
return goToPanoramaCLubItemMenu();
default:
Toast.makeText(activity.getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
}
);
}
As you see im trying to get the current location of menuItem on the screen using TreeObserver. I know that observer works after something happens, meaning its not working right after its called. But anyway the menuButton view is always null

The override method onBackPressed doesn't work when showing popup window

I want to handle the back press event when showing a popup window in android.
I do like this.
In the fragment:
#Override
public boolean onBackPressed() {
if (backPressStrategy == BACK_PRESS_PLAN_A) {
if (guideDialog != null) {
guideDialog.dismiss();
}
closeFlashPay(REQ_CLOSE_FLASH_PAY_AND_FINISH);
return true;
} else if (backPressStrategy == BACK_PRESS_PLAN_B) {
if (guideDialog != null) {
guideDialog.dismiss();
}
getActivity().finish();
return true;
} else {
return false;
}
}
And in the Activity, I do like this
#Override
public void onBackPressed() {
PayBaseFragment contentFragment = (PayBaseFragment) getSupportFragmentManager().findFragmentByTag(TAG_CONTENT_FRAGMENT);
if (contentFragment != null && contentFragment.onBackPressed()) {
return;
}
super.onBackPressed();
}
The problem is, the first time when I pressed back button, the popupwindow just disappeared and the override onBackPressed method was not invoked. Unless I press back button two times.
I show my popup window like this
guideDialog.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
Thanks for help
You need to handle the back button key of your dialog with this :
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
// you can call your onBackPress here
}
return true;
}
});

How to control navigation history in webview inside fragment

I have a webview inside fragment and I want it to be controlled by the navigation history whenever I press the back button.
In my case, when I press the back button I leave the webview, but I want that on pressing the button I will return to the state that is stored in the navigation history (from before leaving the webview).
Any solution please?
I tried with onKey but it does not resolve my problem. Here my code:
public class FragmentAll extends Fragment implements
DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
OnDownloaExpodTerminated {
public static Fragment newInstance(Context context) {
FragmentAll f = new FragmentAll();
return f;
}
private WebView myWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
(((MainActivity) getActivity()) ).setActionBarTitle("Store");
myWebView = (WebView) v.findViewById(R.id.webView1);
setWebview();
v.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
if (arg1 == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return false;
}
});
return v;
}
...
}
You can try it
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
// Otherwise defer to system default behavior.
super.onBackPressed();
}
You will have to make a method inside your Fragment class:
public void goBackWebview(){
myWebview.goBack();
}
Now, go to the Activity class to which this fragment is attached and override the onBackPressed():
#Override
public void onBackPressed() {
//if webview has history
myFragment.goBackWebView();
}
you need to manage list of links is loaded in your webview.
you can get the url like this
web_des2.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
HitTestResult hitTestResult = web_des2.getHitTestResult();
if (hitTestResult != null) {
String url = hitTestResult.getExtra();
if (url != null && url.startsWith("http://")) {
yourUrlList.add(url);
web_des2.loadUrl(url);
}
}
return true;
}
return false;
}
});
you can check onBackPress if your list does not empty then get url form list and load it into webview and remove from the list.
you can use Stack to store url so become easy you can use pop() and push() function directly. if like than +1

Detect menu button event

I want to disable menu button. I read a lot of articles and nothing works.
I can't even detect menu button pressed event. Overriding methods like
onKeyDown(), onKeyUp(), onPrepareOptionsMenu(), onCreateOptionsMenu() didn't
worked. I am really desperate here, please help.
public class MainActivity extends Activity{
TranslateAnimation animateTopLayer;
Button btnOk;
ImageView ivLockMechanism;
ViewGroup rlTopLayer;
FramesSequenceAnimation anim;
#Override
public void onAttachedToWindow() {
getWindow().addFlags(WindowManager.LayoutParams. FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent lockServiceIntent = new Intent(getApplicationContext(),LockService.class);
startService(lockServiceIntent);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.test);
rlTopLayer = (ViewGroup) findViewById(R.id.rlTopLayer);
ivLockMechanism = (ImageView) findViewById(R.id.ivLockMechanism);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rlTopLayer.startAnimation(animateTopLayer);
}
});
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.pg_0);
ivLockMechanism.setImageBitmap(b);
anim = AnimationsContainer.getInstance().unlockMechanismAnimation(ivLockMechanism);
animateTopLayer = new TranslateAnimation(0, 500,0, 0);
animateTopLayer.setDuration(1000);
animateTopLayer.setFillAfter(true);
animateTopLayer.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
anim.start();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( Integer.valueOf(android.os.Build.VERSION.SDK) < 7
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
}
if (keyCode == KeyEvent.KEYCODE_MENU){
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
return;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
This works for me:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
return true;
}
return super.onKeyDown(keyCode, event);
}
Return true to prevent this event from being propagated further, or
false to indicate that you have not handled this event and it should
continue to be propagated.
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
return false;
}

How to add "Go Back" function in WebView inside Fragment?

UPDATE: Solved! Problem was related to my Viewpager not WebView.
I'm trying to add a "Go Back" function to my WebView which is inside a Fragment. But I can't figure out how to:
public final class TestFragment extends Fragment {
static WebView mWeb;
private View mContentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mContentView = inflater.inflate(R.layout.webview, null);
mWeb = (WebView)mContentView.findViewById(R.id.webview);
WebSettings settings = mWeb.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(false);
mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWeb.getSettings().setBuiltInZoomControls(false);
mWeb.loadUrl("myurl...");
mWeb.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
mWeb.goBack();
return true;
}
return false;
}
});
}
}
I also tried something like:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
mWeb.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Another solution but same problem:
#Override
public void onBackPressed()
{
if(webView.canGoBack())
webView.goBack();
else
super.onBackPressed();
}
Any ideas how to get this working?
Perhaps its android restriction. Try to do this using handler.
public final class TestFragment extends Fragment {
static WebView mWeb;
private View mContentView;
private Handler handler = new Handler(){
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:{
webViewGoBack();
}break;
}
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.webview, null);
mWeb = (WebView)mContentView.findViewById(R.id.webview);
WebSettings settings = mWeb.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(false);
mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWeb.getSettings().setBuiltInZoomControls(false);
mWeb.loadUrl("myurl...");
mWeb.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWeb.canGoBack()) {
handler.sendEmptyMessage(1);
return true;
}
return false;
}
});
}
private void webViewGoBack(){
mWeb.goBack();
}
}
You can check this code :
webView.canGoBack();
webView.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:
Override the onBackPressed inside the activity.
When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
If it is, ask the fragment if the webview can go back.
if it is not, call the super or whatever you need
Edit:
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentByTag("webview");
if (webview instanceof MyWebViewFragment) {
boolean goback = ((MyWebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}
I've created a simple interface:
public interface IOnBackPressed {
boolean onBackPressed();
}
in the Activity:
public class MyActivity extends Activity {
#Override public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
super.onBackPressed();
}
}
}
in the Fragment:
public class MyFragment extends Fragment implements IOnBackPressed {
#Override
public boolean onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
// backpress is not considered in the Activity
return true;
} else {
// activity will act normal
return false;
}
}
}
In WebViewActivity.java, I added 1 method:
#Override
public void onBackPressed() {
WebViewFragment fragment = (WebViewFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
if (fragment.canGoBack()) {
fragment.goBack();
} else {
super.onBackPressed();
}
}
In WebViewFragment.java, I added 2 methods:
public boolean canGoBack() {
return mWebView.canGoBack();
}
public void goBack() {
mWebView.goBack();
}
#RomanBlack's answer gave me the right idea, but since we use kotlin I had to adapt the answer a little bit.
webView.setOnKeyListener { _, _, keyEvent ->
if (keyEvent.keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
false
} else if (keyEvent.keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == MotionEvent.ACTION_UP) {
webView.goBack()
true
} else true
}
if you want to do it with returns you have to add something like:
return#setOnKeyListener true
There is a simple way with BackPressedDispatcher
Fragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if(webView.canGoBack()){
webView.goBack()
} else {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
requireActivity().onBackPressedDispatcher.addCallback(this,callback)
}
Activity :
override fun onBackPressed() {
val fragment = supportFragmentManager.findFragmentByTag("WebViewFragment")
if (WebViewFragment::class.java.isInstance(fragment)) {
if (onBackPressedDispatcher.hasEnabledCallbacks()) {
onBackPressedDispatcher.onBackPressed()
return
}
super.onBackPressed()
}
}
Maybe these codes can be improved, but it works very well for me. For more information visit here.
my solution was in fragment I added to public methods
public static boolean canGoBack(){
return mWebView.canGoBack();
}
public static void goBack(){
mWebView.goBack();
}
then from activity I call
#Override
public void onBackPressed() {
if(webFragment.canGoBack()){
webFragment.goBack();
}else{
super.onBackPressed();
}
}
note The mwebview is static
you can do this by :
in the Activity put :
// Set WebView
public void setWebView(WebView web) {
this.web = web;
}
in the web fragment after ActivityCreated() put:
((Your_Activity) getActivity()).setWebView(webView);
Don't forget to set webView from the onCreateView() like these:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
webView = (WebView) inflater.inflate(R.layout.your_web_fragment, container,
false);
return web;
}
#OmidAmnivia answer is correct your app the solution to the crash is
#Override
public void onBackPressed() {
if(webFragment.isInitialized && webFragment.canGoBack()){
webFragment.goBack();
}else{
super.onBackPressed();
}
}
You have to check whether your class has been initialised or not.
This is how I did in my app. I consume back press event till web view can go back. Once web view cant go back I show hint to user that if he keep on pressing back then app will exit.
It will give user a chance to stay in your app when webview cant go back. I felt it more user friendly:
//time passed between two back presses.
private val TIME_INTERVAL = 200
// variable to keep track of last back press
private var mBackPressed: Long = 0
webView!!.requestFocus()
webView.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.action == MotionEvent.ACTION_UP
) {
if(webView.canGoBack()) {
//go back in previous page
webView.goBack()
return#OnKeyListener true
}
else
{
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{ // dont consume back press and pass to super
return#OnKeyListener false
}
else {
// show hint for double back press
Toast.makeText(context, " Double Tap back button to exit the demo", Toast.LENGTH_SHORT).show();
mBackPressed = System.currentTimeMillis();
return#OnKeyListener true
}
}
}
return#OnKeyListener false
})
First of all get back pressed in fragment
mContentView.setFocusableInTouchMode(true);
mContentView.requestFocus();
mContentView.setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return false;
}
} );
hope it will works.
This worked in my case
public class FantasyFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
WebView webview;
SwipeRefreshLayout swipeLayout;
String currentUrl="https://www.stackoverflow.com/";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_stadium, container, false);
swipeLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipescreen);
swipeLayout.setOnRefreshListener(this);
return root;
}
#Override
public void onStart() {
super.onStart();
LoadWeb();
}
public void LoadWeb() {
webview = (WebView) getActivity().findViewById(R.id.webview786);
swipeLayout.setRefreshing(true);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webview.getSettings().setAppCacheEnabled(true);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
webview.loadUrl(currentUrl);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Snackbar.make(view, "Connection Error", Snackbar.LENGTH_LONG)
.setAction("Retry", new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadWeb();
}
}).show();
}
#Override
public void onPageFinished(WebView view, String url) {
swipeLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
});
webview.canGoBack();
webview.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& webview.canGoBack()) {
webview.goBack();
return true;
}
return false;
}
});
}
#Override
public void onRefresh() {
LoadWeb();
}
}
The simplest answer is jut to setOnKeyListeneron into webView itself:
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if( keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
webView.goBack();
return true;
}
}
return false;
}
});

Categories

Resources