I'm having a trouble with findViewByid
but I can't find where the problem is.
Here's my FirstFragment
class code:
import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import java.util.ArrayList; import java.util.List; public class FirstFragment extends Fragment { public static final String TAG = "first"; private WebView mWebView; ProgressBar progressBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWebView = (WebView) findViewById(R.id.activity_main_webview); progressBar = (ProgressBar) findViewById(R.id.progressBar1); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.loadUrl("http://www.google.com"); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.secondefragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }
FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .
findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
You need to do this in onCreateView:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.secondefragment, container, false); mWebView = (WebView) view.findViewById(R.id.activity_main_webview); progressBar = (ProgressBar) view.findViewById(R.id.progressBar1); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.loadUrl("http://www.google.com"); return view; }
Fragment
doesn't provide thefindViewById()
method. This is provided in Activity
or View
. When implementing a Fragment
you don't inflate your views in onCreate()
(like you normally do in an Activity
.) Instead, you do it in onCreateView()
and you need to use the inflated root View
to find the ID within the layout you inflated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With