2016-05-18 82 views
0

所以我有在XML佈局文件中的以下片段:Android的 - 顯示的WebView的片段

<RelativeLayout 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" 
    tools:context="com.example.dwinnbrown.myapplicationv20.MainFragment"> 

    <!-- TODO: Update blank fragment layout --> 
    <WebView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/webView" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentStart="true" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentEnd="true" /> 

</RelativeLayout> 

我現在想一個url加載到通過與該片相關的Java文件的Web視圖。不過,我遇到了一個錯誤「無法解析findViewByID(int)」。有任何想法嗎?

這裏是我試圖用碎片的代碼:

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.WebView; 


/** 
* A simple {@link Fragment} subclass. 
*/ 
public class MainFragment extends Fragment { 

    public MainFragment() { 
     // 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_main, container, false); 


     String url = "http://winn-brown.co.uk/"; 
     WebView view = (WebView) this.findViewById(R.id.webView); 
     view.getSettings().setJavaScriptEnabled(true); 
     view.loadUrl(url); 
    } 



} 

回答

1

做這樣的事情

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_main, container, false); 

    String url = "http://winn-brown.co.uk/"; 
    WebView view = (WebView) rootView.findViewById(R.id.webView); 
    view.getSettings().setJavaScriptEnabled(true); 
    view.loadUrl(url); 

    return rootView ; 
} 
+0

嗯錯誤「的觀點已經在範圍內定義」。它在這條線上失敗:'WebView view =(WebView)view.findViewById(R.id.webView);' – dwinnbrown

+0

我更新了代碼,請嘗試更新代碼。 – Masum

+0

完美!將標記答案一旦我可以:) – dwinnbrown