Can Not Resolve Method 'findviewbyid(int)'
Solution 1:
You need to do this in onCreateView:
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Viewview= inflater.inflate(R.layout.secondefragment, container, false);
mWebView = (WebView) view.findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
WebSettingswebSettings= mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
return view;
}
Solution 2:
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.
Solution 3:
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.
publicinterfaceMyInterfcae { voidshowTextView(); }
Then your activity implements that Interface.
publicclassMyActivityextendsActivityimplementsMyInterfcae { @OverridepublicvoidshowTextView(){ findViewById(R.id.textview).setVisibility(View.VISIBLE); } }
In that fragment grab a reference to the interface.
MyInterfacemif= (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.
Solution 4:
I had this problem when I downloaded sample project from github. This project had
compileSdkVersion 23
buildToolsVersion "23.0.0"
targetSdkVersion 23
in Activity context
and findViewById()
were in red color inside onCreate() method. So I updated the above versions to
compileSdkVersion 25
buildToolsVersion "25.0.3"
targetSdkVersion 25
and error got resolved.
Solution 5:
I meet the same question in Android studio learning,just because I create the project by Fragment
. Choose Blank Activity
with no Fragment
would solve it.
Post a Comment for "Can Not Resolve Method 'findviewbyid(int)'"