简体   繁体   中英

Android WebView Refresh Page and Display Toast [HW]

This is for study and I just want to make sure my answers are 100% right. The question gives me skeleton code and I'm required to fill it in. Here is the code.

public class WebFragment extends WebViewFragment {

   private WebView mWebView;

   @Override
   public void onActivityCreated(Bundle.savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      // Fill in here
   }

   public void refreshPage(View view) {
       // Fill in here
   }

}

Now I am asked three questions. I have put my answers below each question.

a. Instantiate the WebView property in the class

b. When the activity has started, make the WebView component load the url " http://www.google.com/ "

   @Override
   public void onActivityCreated(Bundle.savedInstanceState) {
      super.onActivityCreated(savedInstanceState);

      mWebView = (WebView) findViewById(R.id.webview);  // question a
      mWebView.getSettings().setJavaScriptEnabled(true); // question a
      mWebView.loadUrl("http://www.google.com");  // question b
   }

c. Assuming a button is available in the activity layout and runs refreshPage when pressed, make the function reload the WebView page and show a Toast with the message "Page has been refreshed!"

   public void refreshPage(View view) {
       mWebView.reload();
       Toast toast = Toast.makeText(getApplicationContext(), "Page has been refreshed!"), Toast.LENGTH_SHORT().show();

   }

Any feedback is appreciated.

answer a seems ok, for the toast you don't need the variable, unless you don't want to do something other than showing the toast

mWebView.reload();
Toast.makeText(getApllicationContext(),"foo",Toast.LENGTH_SHORT).show();

or pass a custom time in milliseconds

Toast.makeText(getApllicationContext(),"foo",2000).show();

you can also initialize a Toast variable and than call show on it, it works, it's just a useless variable if you're not going to do anything with it but it's not wrong

Toast toast = Toast.makeText(getApplicationContext(),"foo",1000);
toast.show();

oh, I don't know if it's required, but like this refreshPage method is not callable by anybody, maybe you want to set an OnClickListener to the button (that we assume is in the layout) so that refreshPage can be called

((Button)findViewById(R.id.buttonId)).setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v){
        refreshPage(v);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM