Search code examples
androidandroid-webviewfindviewbyid

findViewById failing to build WebView


public class FeedFragment extends Fragment {
private WebView livestream;


public FeedFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_feed, container, false);

    livestream = (WebView) WebView.findViewById(R.id.livestream);
    livestream.loadUrl("http://www.google.com");

}

Why am I getting the following errors:

error: non-static method findViewById(int) cannot be referenced from a static context where T is a type-variable: T extends View declared in method findViewById(int)

I'm tired of wasting my time reading the android documentation and coming up with errors!

Fragment xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffb067"
tools:context=".FeedFragment">

<!-- TODO: Update blank fragment layout -->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:textColor="@android:color/white"
    android:textSize="20sp"
    android:textStyle="bold"
    android:text="Feed Fragment" />

<WebView
    android:id="@+id/livestream"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>

Solution

  • use this

     @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            livestream = (WebView) view.findViewById(R.id.livestream);
            livestream.loadUrl("http://www.google.com");
    }
    

    and delete these lines from onCreateView :

    livestream = (WebView) WebView.findViewById(R.id.livestream);
    livestream.loadUrl("http://www.google.com");