WebView Go Back Button inside Fragment - java

Inside a fragment, I'm using WebView. I simply query 2 options when Back Button Clicked
First if; url.equals("www.google.com") [which works perfectly]
Second if; !url.equals("www.google.com") [doesn't work]
I worked in debug mode, but my second if doesn't work, even though url is different than "google.com" and closes the app!
Fragment.Java
#Override
public void onResume() {
super.onResume();
if (getView() == null) {
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if(url.equals("https://www.google.com")){
//normal geri
final AlertDialog.Builder builder_question1 = new AlertDialog.Builder(getContext());
builder_question1.setTitle("Are you sure to close the app?");
builder_question1.setCancelable(true);
//POSITIVE BUTTON
builder_question1.setPositiveButton("yes",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
System.exit(0);
}
});
//NEGATIVE BUTTON
builder_question1.setNegativeButton("no",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//do something...
//and dismiss
dialogInterface.dismiss();
}
});
builder_question1.create().show();
}
if(!url.equals("https://www.google.com")){
if(webView.canGoBack()){
webView.goBack();
}
}
}
return true;
}
});
}
WebViewClient
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Toast.makeText(getContext(), ""+url, Toast.LENGTH_SHORT).show();
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
// Toast.makeText(getContext(), "page loaded", Toast.LENGTH_SHORT).show();
super.onPageFinished(view, url);
}
});
webView.loadUrl(url);

Apply Back button in activity containing fragment

it's one of an issue, the application gets crash for a second time because of wrong context type in dialog builder when you try to display the dialog.
Change the AlertDialog context from getContext() to getActivity(); and System.exit(0); with getActivity().finish();
final AlertDialog.Builder builder_question1 = new AlertDialog.Builder(getActivity());
builder_question1.setTitle("Are you sure to close the app?");
builder_question1.setCancelable(true);
//POSITIVE BUTTON
builder_question1.setPositiveButton("yes",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().finish();
}
});
if(!url.equals("https://www.google.com")){
if(webView.canGoBack()){
webView.goBack();
return false;
}
}

Maybe this helps you
if(url.equals("https://www.google.com")){
//normal geri
} else {
if(webView.canGoBack()){
webView.goBack();
}
}

Related

Why Can't I See The Soft Keyboard When I Inflate A Layout With A WebView?

I have a donation option on my app in the menu. When the user taps on that an AlertDialog.Builder appears that will display a layout with a webviewer on it. The page loads just fine in the WebViewer in the AlertDialog. However, when the webpage loads and there is a editable text view on the webpage the keyboard will not popup to allow users to enter in their dollar amount. Here is what I tried...
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setIcon(R.drawable.ic_baseline_payment_32);
adb.setTitle("Tip Developer");
View v = getLayoutInflater().inflate(R.layout.tip_developer_layout, null);
WebView wv = v.findViewById(R.id.tip_donation_webViewer);
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.loadUrl("");
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
wv.requestFocusFromTouch();
wv.requestFocus(View.FOCUS_DOWN);
}
});
wv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus())
{
v.requestFocus();
}
break;
}
return false;
}
});
adb.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setView(v);
adb.create();
adb.show();
I appreciate the help!
Insert this code.
private void showSoftKeyBoard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
Then, implement it in OnCLick.
wv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSoftKeyBoard();
}
});
Add this line in your EditText.
android:inputType="number"
And insert this code.
#Override
public void onResume() {
super.onResume();
wv.setFocusableInTouchMode(true);
wv.requestFocus();
}

How to create a dialog outside MainActivity in android

I want to insert an alert dialog into my android app.
It's fine when I follow the tutorial to add it in a simple project, which only has a MainActivity.java, activity_main.xml and a layout xml.
However, when I want to insert the code into my project, I get some questions.
My code is:
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Are you sure want to QUIT ?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
pmaControllerManager.OnExit();
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
})
.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.show();
There is a warning symbol in the this in the first line.
How could I fix it?
p.s. below is the function where I call showDialog(I call it in buttons[5]):
private void setbutton()
{
buttons[0]=(ImageButton)menu.findViewById(R.id.button0);
buttons[1]=(ImageButton)menu.findViewById(R.id.button1);
buttons[2]=(ImageButton)menu.findViewById(R.id.button2);
buttons[3]=(ImageButton)menu.findViewById(R.id.button3);
buttons[4]=(ImageButton)menu.findViewById(R.id.button4);
buttons[5]=(ImageButton)menu.findViewById(R.id.button5);
buttons[1].setBackgroundResource(R.drawable.screen);
buttons[2].setBackgroundResource(R.drawable.sketch);
buttons[3].setBackgroundResource(R.drawable.importdraw);
buttons[4].setBackgroundResource(R.drawable.setting);
buttons[5].setBackgroundResource(R.drawable.out);
center.setBackgroundResource(R.drawable.noticeicon_using);
/*center.setOnClickListener(new ImageButton.OnClickListener(){
#Override
public void onClick(View v) {
if(click)
{
closemenu();
//mode=false;
}
else
{
openmenu();
//mode=true;
}
click=!click;
}
});*/
center.setOnTouchListener(new View.OnTouchListener() {
boolean isMove=false;
int touchy,touchx,y;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action=motionEvent.getAction();
if(action==MotionEvent.ACTION_DOWN)
{
y=params.y;
//Log.i("y:",String.valueOf(y));
touchy=(int)motionEvent.getRawY();
touchx=(int)motionEvent.getRawX();
}
else if(action==MotionEvent.ACTION_MOVE)
{
if(Math.abs(motionEvent.getRawX()-touchx)<30)
{
isMove=true;
params.gravity=Gravity.RIGHT;
params.y=y+(int)motionEvent.getRawY()-touchy;
wm.updateViewLayout(center,params);
wm.updateViewLayout(menu,params);
}
}
else if(action==MotionEvent.ACTION_UP)
{
if(!isMove)
{
if(click)
{
closemenu();
//mode=false;
}
else
{
openmenu();
//mode=true;
}
click=!click;
}
else
isMove=false;
}
return true;
}
});
buttons[1].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[1].setBackgroundResource(R.drawable.screen_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[1].setBackgroundResource(R.drawable.screen);
pmaControllerManager.newTask("screen");
}
return true;
}
});
buttons[2].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[2].setBackgroundResource(R.drawable.sketch_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[2].setBackgroundResource(R.drawable.sketch);
pmaControllerManager.newTask("sketch");
}
return true;
}
});
buttons[3].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[3].setBackgroundResource(R.drawable.importdraw_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[3].setBackgroundResource(R.drawable.importdraw);
}
return true;
}
});
buttons[4].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[4].setBackgroundResource(R.drawable.setting_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[4].setBackgroundResource(R.drawable.setting);
pmaControllerManager.Setting();
}
return true;
}
});
buttons[5].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
buttons[5].setBackgroundResource(R.drawable.exit_focus);
else if(event.getAction()==MotionEvent.ACTION_UP)
{
buttons[5].setBackgroundResource(R.drawable.out);
shoaDialog(menuwindow.this);
pmaControllerManager.OnExit();
}
return true;
}
});
}
Pass Context instead of this because this is a reference to the current object. It means if you call it for example from lambda this will be a reference of object which is extended from anonymous class.
so you can make method like
public void showDialog(Context context) {
AlertDialog alartDialog = AlertDialog.Builder(context).
...
.show();
}
and then call it like
showDialog(MainActivity.this); //for activity
showDialog(MainFragment.this.getActivity()); //for fragment
By the way better to make something like Util class for it:
class DialogUtil {
public static void showDialog(Context context) {
AlertDialog alartDialog = AlertDialog.Builder(context).
...
.show();
}
}
Then call it like
DialogUtil.showDialog(MainActivity.this); //for activity
DialogUtil.showDialog(MainFragment.this.getActivity()); //for fragment
UPDATE
Instead of calling it like:
shoaDialog(menuwindow.this);
You can pass Context as I described above or you can get it from View:
buttons[5].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//some code here
showDialog(v.getContext());
return true;
}
});
replace this to MainActivity.this like :
android.app.AlertDialog alartDialog = new
android.app.AlertDialog.Builder(MainActivity.this)
The AltertDialog requires a context and you are passing it the activity. Try using
new android.app.AlertDialog.Builder(this.getApplicationContext())
instead.
Replace this with MainActivity.this or getApplicationContext()
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(MainActivity.this)
If you are using dialog look below :
For Activity : ActivityName.this
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(MainActivity.this)
For Fragment : getActivity()
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(getActivity())
For Adapter : Context context;
android.app.AlertDialog alartDialog = new android.app.AlertDialog.Builder(context)
Also, Look into this Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Android Java Implement KEYCODE_VOLUME_UP and DOWN to my code

I wonder how to implement KEYCODE_VOLUME_UP and DOWN to my code. So every time when I press the volume up or down key will simultaneously reflect on my Notification Volume Control app.
The method I want to implement is as follows which will make my own app volume up and down when the physical volume up and down button is pressed:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return false;
}
}
The code I want to implement to is:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
run();
}
public void run()
{
mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
final LayoutInflater inflater =
(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View ViewLayout = inflater.inflate(R.layout.activity_main,
(ViewGroup)findViewById(R.id.activity_main));
alarm=(SeekBar)ViewLayout.findViewById(R.id.alarm);
music=(SeekBar)ViewLayout.findViewById(R.id.music);
ring=(SeekBar)ViewLayout.findViewById(R.id.ring);
system=(SeekBar)ViewLayout.findViewById(R.id.system);
voice=(SeekBar)ViewLayout.findViewById(R.id.voice);
alarmVol=(TextView)ViewLayout.findViewById(R.id.alarmVol);
musicVol=(TextView)ViewLayout.findViewById(R.id.musicVol);
ringVol=(TextView)ViewLayout.findViewById(R.id.ringVol);
systemVol=(TextView)ViewLayout.findViewById(R.id.systemVol);
voiceVol=(TextView)ViewLayout.findViewById(R.id.voiceVol);
alertDialogBuilder = new AlertDialog.Builder(this);
//alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
//alertDialogBuilder.setTitle("Volume Control");
alertDialogBuilder.setView(ViewLayout);
initBar(alarm, AudioManager.STREAM_ALARM, alarmVol);
initBar(music, AudioManager.STREAM_MUSIC, musicVol);
initBar(ring, AudioManager.STREAM_RING, ringVol);
initBar(system, AudioManager.STREAM_SYSTEM, systemVol);
initBar(voice, AudioManager.STREAM_VOICE_CALL, voiceVol);
alertDialogBuilder.create();
alertDialogBuilder.show();
}
private void initBar(SeekBar bar, final int stream, final TextView textView)
{
final float maxVolume=mgr.getStreamMaxVolume(stream);
float curVol = mgr.getStreamVolume((stream));
bar.setMax((int)maxVolume);
bar.setProgress((int)curVol);
bar.setKeyProgressIncrement(1);
textView.setText(String.valueOf((int)(curVol/maxVolume*100)));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
mgr.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
textView.setText(String.valueOf((int)
((progress/maxVolume)*100)));
}
public void onStartTrackingTouch(SeekBar bar) {
}
public void onStopTrackingTouch(SeekBar bar) {
}
});
}
}

why the progress dialog doesn't disappear on some page?

this is my mainactivity, when i load some page the progress dialog doesn't disappear onpagefinished...where is the problem?
if you want to try the problem are with the page "accedi" or on the payment of the order
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
webView.setClickable(true);
webView.setFocusableInTouchMode(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://www.alldrink.it");
WebClientClass webViewClient = new WebClientClass();
webView.setWebViewClient(webViewClient);
WebChromeClient webChromeClient=new WebChromeClient();
webView.setWebChromeClient(webChromeClient);
setContentView(webView);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
}
public class WebClientClass extends WebViewClient {
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Attendere");
pd.setMessage("Caricamento in corso..");
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
if (pd.isShowing()) {
pd.dismiss();
}
}
}
public class WebChromeClass extends WebChromeClient{
}
}
the dismiss() function is working, but your onPageStarted() has run two times, making dialog recreate again and look like it never disappear. Try changing your onPageStarted as:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(!pd.isShowing())
{
pd.setTitle("Attendere");
pd.setMessage("Caricamento in corso..");
pd.show();
}
}

One of webview reload page after change screen orientation

First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"

Categories

Resources