Can not resolve method 'findViewById(int)'
You need to do this in onCreateView:
@Overridepublic 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.
getActivity().findViewById()
works. However, this isn't a good practice because the fragment may be reused in another activity.
The recommended way for this is to define an interface.
The interface should contain methods by which the fragment needs to communicate with its parent activity.
public interface MyInterfcae { void showTextView();}
Then your activity implements that Interface.
public class MyActivity extends Activity implements MyInterfcae { @Override public void showTextView(){ findViewById(R.id.textview).setVisibility(View.VISIBLE); }}
In that fragment grab a reference to the interface.
MyInterface mif = (MyInterface) getActivity();
Call a method.
mif.showTextView();
This way, the fragment and the activity are fully decoupled and every activity which implements that fragment, is able to attach that fragment to itself.