我在使用片段填充listview时出现问题,我有一个名为 PagesFragment 的片段类,它扩展了Fragment ..我还有一个MainActivity,可以使用菜单在我的片段之间切换。
我相信我需要扩展ListFragment以便在我的片段' PagesFragment' 中填充我的列表视图,但是当我更改所有类以扩展ListFragment并更改我的案例时在我的MainActivity中的ListFragement中,当我尝试运行我的代码时出现错误:
您的内容必须包含一个ListView,其id属性为' android.R.id.list'
注意:即使将我的id属性更改为正确的值,我仍然会收到错误。
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
ListFragment listfragment = null;
switch (position) {
case 0:
listfragment = new HomeFragment();
break;
case 1:
listfragment = new FindPeopleFragment();
break;
case 2:
listfragment = new PhotosFragment();
break;
case 3:
listfragment = new CommunityFragment();
break;
case 4:
listfragment = new PagesFragment();
break;
case 5:
listfragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (listfragment != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, listfragment)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
public class PagesFragment extends ListFragment
{
// Counter for checking if Parsed Values are empty - To tell user event has not started
int counter;
int ButtonCounter = 0;
private String gamename;
private String gamedate;
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog pDialog2;
private EditText editText;
private TextView textView;
private ListView list1;
//Main variables
private static String pt;
private static String pd;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> inboxList;
// products JSONArray
JSONArray inbox = null;
JSONArray tour = null;
// Inbox JSON url
private static final String INBOX_URL = "http://www…";
// ALL JSON node namesapi_key=tD3djFMGmyWmDUdcgmBVFCd3
private static final String TAG_MESSAGES = "p";
private static final String TAG_ID = "p";
private static final String TAG_FROM = "g";
private static final String TAG_EMAIL = "t";
private static final String TAG_SUBJECT = "r";
private static final String TAG_DATE = "s";
private static final String TAG_TOUR = "t";
private static final String TAG_TOURDATE = "d";
public PagesFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.women_list, container, false);
list1 = (ListView) rootView.findViewById(android.R.id.list);
new LoadInbox().execute();
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Hashmap for
inboxList = new ArrayList<HashMap<String, String>>();
/**
* Background Async Task to Load all INBOX messages by making HTTP Request
* */
Log.d("ITS RUNNING!", "Log Message");
new LoadInbox().execute();
}
private void populateList()
{
}
class LoadInbox extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute ()
{
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
/**
* getting Inbox JSON
* */
}
protected void onPostExecute(String file_url)
{
Log.d("Comments", "DoInBackground");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, "GET",
params);
try {
Log.d("Comments", "Try Try Try Try");
inbox = json.getJSONArray(TAG_MESSAGES);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++)
{
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
//Get TOURNAMENT NAME
pgatour = c.getString(TAG_TOUR);
//Get TOURNAMENT DATE
tourdate = c.getString(TAG_TOURDATE);
//Get GOLFER NAME
String from = c.getString(TAG_FROM);
if(from != null && !from.isEmpty())
{
}
//check if blank
else
{
from = "--";
counter++;
}
//GET THUR
String mailer = c.getString(TAG_EMAIL);
if(mailer != null && !mailer.isEmpty())
{
}
else{ mailer = "--";}
///GET ROUND
String subject = c.getString(TAG_SUBJECT);
if(subject != null && !subject.isEmpty())
{
}
else{ subject = "--";}
///GET SCORE
String date = c.getString(TAG_DATE);
if(date != null && !date.isEmpty())
{
}
else
{ subject = "--";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, from);
map.put(TAG_EMAIL, mailer);
map.put(TAG_DATE, date);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
inboxList.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
if( pgatour != null)
{
}
else
{
}
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
//This is for displaying the TOUR NAME & Data above button
textView = (TextView) getView().findViewById(R.id.textView6);
textView.setText(" "+ pt + " - " + pd);
/**
* Updating parsed JSON data into ListView
* */
Log.d("Comments", "pt" +pd );
ListAdapter adapter = new SimpleAdapter(
getActivity(), inboxList,
R.layout.women_list_item, new String[] { TAG_ID, TAG_FROM,TAG_DATE,TAG_EMAIL,TAG_SUBJECT},
new int[] { R.id.from, R.id.subject, R.id.date,R.id.mail,R.id.roundscore });
// updating listview
list1.setAdapter(adapter);
}
});
//class end
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<TextView
android:id="@+id/textView1"
android:text="POS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView2"
android:text="G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView3"
android:text="S"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView4"
android:text="T"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
<TextView
android:id="@+id/textView5"
android:text="R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:textSize="11dp"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:background="#E5E4E2"
android:divider="#736F6E"
android:dividerHeight="4px"
android:padding="8dp"
android:layout_weight="1.0"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="0"
android:textSize="12dp"
android:textColor="#90d2c6"
android:layout_centerVertical="true"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:text="Refresh Scores"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:textSize="11dp"
android:layout_weight="1"
/>
</RelativeLayout>
</LinearLayout>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
09-21 17:18:34.873:E / AndroidRuntime(3814):致命异常:主要 09-21 17:18:34.873:E / AndroidRuntime(3814):进程:info.androidhive.slidingmenu,PID:3814 09-21 17:18:34.873:E / AndroidRuntime(3814):java.lang.RuntimeException:无法启动活动ComponentInfo {info.androidhive.slidingmenu / info.androidhive.slidingmenu.MainActivity}:java.lang.RuntimeException:你的content必须有一个ListView,其id属性为&#39; android.R.id.list&#39; 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.access $ 800(ActivityThread.java:148) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1292) 09-21 17:18:34.873:E / AndroidRuntime(3814):at andr oid.os.Handler.dispatchMessage(Handler.java:102) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.os.Looper.loop(Looper.java:135) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.main(ActivityThread.java:5312) 09-21 17:18:34.873:E / AndroidRuntime(3814):at java.lang.reflect.Method.invoke(Native Method) 09-21 17:18:34.873:E / AndroidRuntime(3814):at java.lang.reflect.Method.invoke(Method.java:372) 09-21 17:18:34.873:E / AndroidRuntime(3814):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:901) 09-21 17:18:34.873:E / AndroidRuntime(3814):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 09-21 17:18:34.873:E / AndroidRuntime(3814):引起:java.lang.RuntimeException:你的内容必须有一个ListView,其id属性为&#39; android.R.id.list&#39; 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.ListFragment.ensureList(ListFragment.java:344) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.ListFragment.onViewCreated(ListFragment.java:145) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556) 09-21 17:18:34.873:E / AndroidRuntime(3814):at和roid.app.Instrumentation.callActivityOnStart(Instrumentation.java:1243) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.Activity.performStart(Activity.java:5969) 09-21 17:18:34.873:E / AndroidRuntime(3814):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277) 09-21 17:18:34.873:E / AndroidRuntime(3814):... 10更多
答案 0 :(得分:3)
根据文档ofandroid:id =&#34; @ id / android:list&#34; ListFragment here。它的一小部分。
ListFragment具有由单个列表视图组成的默认布局。 但是,如果需要,可以通过自定义片段布局 从onCreateView返回您自己的视图层次结构(LayoutInflater, ViewGroup,Bundle)。为此,您的视图层次结构必须包含 具有id&#34; @android:id / list&#34;的ListView对象; (或列出它是否在 代码)
解决方案1 因此,如果要将片段更改为ListFragment,请确保布局文件中listView的ID也必须更改,并且应如下所示
<ListView
android:id="@id/android:list"
>
并且在onCreate里面应该是。
View rootView = inflater.inflate(R.layout.women_list, container, false);
list1 = (ListView) rootView.findViewById(android.R.id.list);
然后设置适配器
或强>
解决方案2
在onCreateView中,您不需要查找视图并使用onStart或onResume中的以下代码直接设置适配器。
setListAdapter(adapter);
或强>
解决方案3
在onViewCreated或更高版本的回调方法中,您使用getListView,如下所示
然后设置适配器...注意 - 如果在onCreateView中使用;它会抛出异常
ListView list1 = getListView()
但请确保您不在其他地方使用相同的布局文件 ListFragment和ListActivity,如果你这样做,你会收到错误。
基于讨论和审判的更新
感谢您简单的布局R.layout.Women_list。我使用它创建了一个示例项目,其中一个主要活动(扩展了AppCompatActivity)和一个Fragment(扩展了ListFragment)在活动中。并再次成功地测试了上述解决方案。
现在来解决你的问题。