我真的很纳闷。我有一个上下文:
Context context= getActivity();
当我在片段中使用context
用于UI时,像webview app这样的东西会给我NullPointerException(Forceclose),但是当我使用getActivity()
时效果很好。有什么区别!?
让我解释一下用法。我有一个名为“A”和“B”的活动。活动“B”从活动“B”继承NavigationDrawer和Actionbar。所以有:
public class B extends A
我们知道在NavigationDrawer中有一个主要内容。活动“B”使用片段来提供主要内容,我在该片段中使用Context。 我真的很想知道!抱歉英语不好。
编辑:这是我的代码:
public class PlaceholderFragment extends Fragment {
public Context context = getActivity();
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_text, container, false);
String text = "<html><head><link href=\"file:///android_asset/style_css.css\" rel=\"stylesheet\" type=\"text/css\"></head> <body class=\"body\"> title1 <hr> <div align=\"center\"> <img src= "+imagePath1_1+" width= \"95% \" /></div>les1</body></html>";
WebView webView= new WebView(context);
webView.loadDataWithBaseURL(null,text, "text/html", "UTF-8", null);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((enhanced) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
如果我使用getActivity();直接这个代码工作。
我尝试了什么:
将context
更改为public和final,并使用简单的TextView
代替WebView。
答案 0 :(得分:5)
让我猜一下......你有NullPointerException吗?因为您的context
值似乎始终为null,因为您声明它是这样的:
public Context context = getActivity();
原因是这段代码在创建Fragment时运行,而且它没有附加到任何Activity的时间,所以getActivity()总是返回null。如果你想让你的代码工作。请放置
context = getActivity()
片段生命周期中的其他地方。