2013-07-02 3 views
0

Mon application a un WebView en haut. Pour montrer des choses, j'utilise Toast. Mais la boîte Toast n'a jamais montré si WebView apparaît, alors qu'avant l'affichage de WebView, Toast est visible. Je me demandais si Toast était probablement couvert par WebView. Quelqu'un at-il eu les mêmes problèmes?1) Différence entre setOnClickListener et onclick 2) comment recharger webview sans recharger d'autres dans la même linearlayout

Merci.

ÉDITION !!! Salut, merci pour toutes vos contributions. J'ai trouvé que j'ai posté une mauvaise question pour mes problèmes. J'ai trouvé que les vrais problèmes sont les suivants. Dans le code, j'utilise setOnClickListener pour enregistrer un rappel pour le bouton. Dans le débogage, j'ai trouvé que le callback n'est pas appelé pour une raison quelconque, donc l'instruction Toast n'est pas appelée, et elle n'est pas couverte par webview.

Ensuite, j'ai essayé les attributs onclick dans la mise en page xml pour définir un callback clickGo pour le bouton. Celui-ci fonctionne quand j'appuie sur le bouton, et le Toast montre. Maintenant, ma question est quelle est la différence entre setOnClickListener et onlick.

Encore une question, dans mon clickGo, j'actualise le webview. Le webview recharge en effet quand le bouton est cliqué. Mais pendant ce temps, le spinner est également rechargé et la position de sélection est réinitialisée au 0-ème. Comment puis-je empêcher cela?

Encore merci!

public class MainActivity extends Activity { 

     JSONArray jArray; 
     String result = null; 
     InputStream is = null; 
     StringBuilder sb=null; 
     private Spinner spinner; 
     private Button btnSubmit; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     addListenerOnButton(); 
     addListenerOnSpinnerItemSelection(); 
     new DownloadTask().execute("www.google.com"); 
     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
     } 

     // Given a string representation of a URL, sets up a connection and gets 
     // an input stream. 
     private String downloadUrl(String urlString) throws IOException { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet get = new HttpGet(urlString); 

     HttpResponse response = httpClient.execute(get); 

     // Build up result 
     return EntityUtils.toString(response.getEntity()); 
     } 

     public void addListenerOnSpinnerItemSelection() { 
     spinner = (Spinner) findViewById(R.id.spinner); 
     spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener()); 
     } 

     public void clickGo(View v) { 
     Toast toast = Toast.makeText(MainActivity.this, 
      "OnClickListener : " + 
       "\nSpinner 1 : "+ String.valueOf(spinner.getSelectedItem()), 
        Toast.LENGTH_SHORT); 
     toast.setGravity(Gravity.TOP, 0, 0); 
     toast.show(); 
     new DownloadTask().execute("www.google.com"); 
     } 

     // get the selected dropdown list value 
     public void addListenerOnButton() { 

     spinner = (Spinner) findViewById(R.id.spinner); 
     btnSubmit = (Button) findViewById(R.id.button); 

     btnSubmit.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

      Toast toast = Toast.makeText(MainActivity.this, 
      "OnClickListener : " + 
       "\nSpinner 1 : "+ String.valueOf(spinner.getSelectedItem()), 
        Toast.LENGTH_SHORT); 
      toast.setGravity(Gravity.TOP, 0, 0); 
      toast.show(); 
      new DownloadTask().execute("www.google.com"); 

     } 

     }); 
    } 
` 
    // Implementation of AsyncTask used to download XML feed from stackoverflow.com. 
    private class DownloadTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... urls) { 
     return downloadUrl(urls[0]); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
     setContentView(R.layout.activity_main); 
     // Displays the HTML string in the UI via a WebView 
     WebView myWebView = (WebView) findViewById(R.id.webview); 
     WebSettings webSettings = myWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     myWebView.loadUrl(result); 
     } 
    } 
    } 



    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" > 
    <LinearLayout android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="horizontal" > 
      <TextView android:id="@+id/text" 
        android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
        android:text="@string/word" /> 
      <Button android:id="@+id/button" 
       android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Go" 
        android:onClick="clickGo" /> 
    </LinearLayout> 
    <Spinner android:id="@+id/spinner" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:entries="@array/dictionaries" 
      android:prompt="@string/dict_prompt" />  

    <WebView android:id="@+id/webview" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" /> 
    </LinearLayout> 
+0

Pouvez-vous nous montrer votre code 'webView'? –

+0

Ce sera la première fois que j'entends qu'un toast est recouvert. Collez également le code pour le Toast. – g00dy

+0

J'ai changé mes questions et j'ai téléchargé mon code. –

Répondre

0

Je pense que cette question pourrait résoudre votre question.

Si cela peut être montré, alors je pense que Toast ne devrait pas être couvert par WebView.

onPageFinished() never called (webview)!

mWebView.setWebViewClient(new WebViewClient() { 
@Override 
public void onPageFinished(WebView view, String url) { 
    super.onPageFinished(mWebView, url); 
    Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
    Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show(); 
} 

}); mWebView.loadUrl ("http://pabebbe.com/m/register");

+0

Merci pour vos commentaires. J'ai changé mes questions et j'ai téléchargé mon code. –

0

aucun pain n'est dessiné avec l'ordre de dessin maximum car ils sont créés pendant l'exécution .. assurez-vous où vous créez votre toast et si c'est vraiment appelé.
EDIT
si votre problème était sur le tirage pour essayer d'utiliser ce code

private void moveViewToFront(View currentView) 
    { 
     ViewGroup vg = ((ViewGroup) currentView.getParent()); 
     vg.bringChildToFront(vg.getChildAt(vg.indexOfChild(currentView))); 
    } 

moveViewToFront((LinearLayout) findViewById(R.id.main_layout_2_linear));//pass your ui element you want to bring to the top 
+0

Merci pour vos contributions. J'ai changé mes questions et j'ai téléchargé mon code. –

0

Pour cela, nous devons ajouter un webviewclient dans Android pour la WebView nous ajoutons dans le fichier XML. Ensuite, nous devons enregistrer le webviewclient avec le WebView que nous créons en utilisant cette méthode.

myWebView.setWebViewClient(new MyWebViewClient()); 

Maintenant, créez un nouveau projet et nommez-le WebViewDemo. Maintenant, créez dans main.xml,

<?xml version="1.0" encoding="utf-8"?> 
<WebView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/webview" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
/> 

un fichier nommé test.html dans le dossier actif et copier ce code en elle. C'est le fichier html que nous chargeons dans le webview.

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" 
    "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"> 
<html> 
<body> 
<a href="http://www.google.com">Google</a> 
<input type="button" value="Click Me" onClick="showAndroidToast('Hello Google!')"  
/> 
<script type="text/javascript"> 
    function showAndroidToast(toast) { 
     Android.showToast(toast); 
    } 

</script> 
</body> 
</html> 

maintenant dans le code Java font référence WebView et chargez le fichier html

WebView myWebView; 
myWebView = (WebView) findViewById(R.id.webview); 
myWebView.loadUrl("file:///android_asset/test.html"); 

activer maintenant le javascript en appelant cette fonction

WebSettings webSettings = myWebView.getSettings(); 
webSettings.setJavaScriptEnabled(true); 

Maintenant, nous devons ajouter l'interface javascript pour écouter les fonctions javascript que nous définissons dans le fichier webview html.

myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); 

// outside oncreate 
public class JavaScriptInterface { 
    Context mContext; 

    /** Instantiate the interface and set the context */ 
    JavaScriptInterface(Context c) { 
     mContext = c; 
    } 

    /** Show a toast from the web page */ 
    public void showToast(String toast) { 
     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
     startActivity(new Intent(WebViewDemo.this, WebViewDemo.class)); 
    } 
} 

Créez maintenant un client WebView pour écouter les activités du navigateur et effectuer une fonction spécifique.

myWebView.setWebViewClient(new MyWebViewClient()); 

private class MyWebViewClient extends WebViewClient { 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     if (Uri.parse(url).getHost().equals("www.coderzheaven.com")) { 
      Toast.makeText(getApplicationContext(), "www.coderzheaven.com",  
Toast.LENGTH_SHORT).show(); 
      return false; 
     } 
     // Otherwise, the link is not for a page on my site, so launch another Activity      
that handles URLs 
     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
     startActivity(intent); 
     return true; 
    } 
} 

Maintenant, nous écoutons le bouton de retour.

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    // Check if the key event was the BACK key and if there's history 
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
     myWebView.goBack(); 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
    } 

Maintenant que le projet est terminé. Maintenant, courez et voyez le résultat. Voici le code java complet pour cet exemple

package com.coderzheaven.pack; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.KeyEvent; 
import android.webkit.WebSettings; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.Toast; 

public class WebViewDemo extends Activity { 

WebView myWebView; 
@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    myWebView = (WebView) findViewById(R.id.webview); 
    myWebView.loadUrl("file:///android_asset/test.html"); 
    WebSettings webSettings = myWebView.getSettings(); 
    webSettings.setJavaScriptEnabled(true); 

    myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); 

    // myWebView.setWebViewClient(new WebViewClient()); 
    myWebView.setWebViewClient(new MyWebViewClient()); 
    } 

    public class JavaScriptInterface { 
    Context mContext; 

    /** Instantiate the interface and set the context */ 
    JavaScriptInterface(Context c) { 
     mContext = c; 
    } 

    /** Show a toast from the web page */ 
    public void showToast(String toast) { 
     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
     startActivity(new Intent(WebViewDemo.this, WebViewDemo.class)); 
    } 
    } 

    private class MyWebViewClient extends WebViewClient { 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     if (Uri.parse(url).getHost().equals("www.google.com")) { 
      // This is my web site, so do not override; let my WebView load the page 
      Toast.makeText(getApplicationContext(), "www.google.com",  
    Toast.LENGTH_SHORT).show(); 
      return false; 
     } 
     // Otherwise, the link is not for a page on my site, so launch another Activity 
    that handles URLs 
     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
     startActivity(intent); 
     return true; 
    } 
    } 

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    // Check if the key event was the BACK key and if there's history 
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
     myWebView.goBack(); 
     return true; 
    } 
    // If it wasn't the BACK key or there's no web page history, bubble up to the 
    default 
    // system behavior (probably exit the activity) 
    return super.onKeyDown(keyCode, event); 
    } 
} 
+1

Merci pour vos contributions. J'ai changé mes questions et j'ai téléchargé mon code. –

Questions connexes