[英]non-static method <T>findViewById(int) cannot be referenced from a static context
[英]Error: Non-static method 'findViewById(int)' cannot be referenced from a static context
我正在使用Android Studio(Beta),並且在'onCreateView()'中使用此java代碼時,出現錯誤。
ListView listView = (ListView) findViewById(R.id.someListView);
這是錯誤:
Non-static method 'findViewById(int)' cannot be referenced from a static context
我該如何解決?
假設你在一個活動中有一個靜態片段內部類:你試圖調用活動的findViewById()
,你不能在一個靜態的內部類中沒有對父項的引用。
在onCreateView()
您需要在剛剛膨脹的根視圖上調用它,例如
ListView listView = (ListView) rootView.findViewById(R.id.someListView);
onCreateView()
不應該是一個靜態方法(我假設你在Activity類中定義它),所以你必須做錯事。
如果在靜態AsyncTask或任何其他類中使用它,則可以將活動作為參數傳遞給方法或構造函數,例如:
活動onCreate:
//Pass activity variable (this)
new Main2Activity.MyTask().execute(this);
課內活動:
private static class MyTask extends AsyncTask<Object, Void, String> {
Main2Activity activity;
@Override
protected String doInBackground(Object... params) {
activity = (Main2Activity)params[0];
....
}
@Override
protected void onPostExecute(String str) {
// Use parameter activity passed to class
WebView webView = activity.findViewById(R.id.web_view);
webView.loadData(str, "text/html; charset=UTF-8", null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_layout, container, false);
ListView listView = (ListView) view.findViewById(R.id.listviewID);
context = getActivity();
return view;
}
你現在可以實現這個...使用視圖變量來訪問oncreateView和getActivity()中的xml ui。findViewById(...)來訪問其他onCreateView()方法。
Inside Activity類
static ListView listView;
listView = (ListView) this.findViewById(R.id.someListView);
要么
創建inside fragmentClass(靜態)
static ListView listView;
listView = (ListView) getActivity().findViewById(R.id.someListView);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.