我試圖在片段中使用ListView
。但是getActivity()
爲空。我已經搜索並找到了關於這個主題的許多線索,但這些並不是很有幫助。
這裏是我的代碼:getActivity爲空
ListView.java
:
package de.listview.example;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
public class ListViews extends ListFragment {
private AdapterView.OnItemClickListener listener;
public void makelist()
{
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
}
MainActivity.java
:
public static class ListFragment extends Fragment
{
Context mContext;
@Override
public void onAttach(Activity activity) {
mContext = getActivity();
Log.i("Event", "onAttach called");
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
ListViews lst = new ListViews();
lst.makelist();
return inflater.inflate(R.layout.whitelist_content, container, false);
}
}
case 2:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new ListFragment())
.commit();
break;
你應該仔細閱讀文檔片段和活性 – Blackbelt
'getActivity ()'爲null,因爲你的'Fragment'還沒有附加到'Activity',這意味着佈局還沒有膨脹。這是標準行爲。你應該熟悉[片段生命週期](http://developer.android.com/guide/components/fragments.html#Lifecycle)。 –