【问题标题】:Switching between Fragments and ListFragments causing errors在 Fragments 和 ListFragments 之间切换导致错误
【发布时间】:2015-09-21 14:15:47
【问题描述】:

我在使用片段填充列表视图时遇到问题,我有一个名为 PagesFragment 的片段类,它扩展了片段。我还有一个 MainActivity,它使用菜单在片段之间切换。

我认为我需要扩展 ListFragment 以便在我的 Fragment 'PagesFragment' 中填充我的列表视图,但是当我更改所有类以扩展 ListFragment 并在我的 MainActivity 中将我的案例更改为 ListFragment ,当我尝试运行我的代码时出现错误:

你的内容必须有一个 id 属性为 'android.R.id.list' 的 ListView

注意:即使将我的 id 属性更改为正确的值后,我仍然会收到错误消息。

切换片段的代码 - 使用 SideMenu

 /**
 * 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);
}

片段代码 - 无法填充 ListView

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 - Women_list.XML:

    <?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>

MainActivity XML 布局:

  <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 必须有一个 id 属性为 'android.R.id.list' 的 ListView 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): 在 android.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):在 java.lang.reflect.Method.invoke(本机方法) 09-21 17:18:34.873: E/AndroidRuntime(3814): 在 java.lang.reflect.Method.invoke(Method.java:372) 09-21 17:18:34.873: E/AndroidRuntime(3814): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) 09-21 17:18:34.873: E/AndroidRuntime(3814): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 09-21 17:18:34.873: E/AndroidRuntime(3814): Caused by: java.lang.RuntimeException: Your content must have a ListView its id attribute is 'android.R.id.list' 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): 在和 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 更多

【问题讨论】:

  • 更新:仍然无法正常工作 - 3 天后出现此错误
  • 更新:感谢 Shadow Droid 提供的出色答案,但所有解决方案均无效。

标签: java android json listview android-fragments


【解决方案1】:

根据 android:id="@id/android:list" 的文档 列表片段here。它的一小部分。

ListFragment 有一个由单个列表视图组成的默认布局。 但是,如果您愿意,可以通过以下方式自定义片段布局 从 onCreateView(LayoutInflater, 视图组,捆绑包)。为此,您的视图层次结构必须包含 id 为“@android:id/list”的 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);

然后设置适配器
OR
解决方案2 在 onCreateView 中,你不需要找到视图,直接在 onStart 或 onResume 中使用以下代码设置适配器。

setListAdapter(adapter); 


解决方案 3
在 onViewCreated 或更高版本的回调方法中,您使用 getListView 如下 然后设置适配器...注意-如果在 onCreateView 中使用;它会抛出异常

ListView list1  = getListView()

但请确保您没有在其他地方使用相同的布局文件 ListFragment 和 ListActivity,如果这样做会出错。

基于讨论和试验的更新
感谢您提供简单的布局 R.layout.Women_list。我使用它创建了一个示例项目,其中一个主 Activity(扩展了 AppCompatActivity)和一个 Fragment(扩展了 ListFragment) 在活动中。并再次对上述解决方案进行了成功测试。

现在来解决你的问题。

  1. 您的应用程序中可能有多个布局,其中可能包含许多列表视图...因此所有列表视图的 id 不必为 @id/android:list 只有那些列表视图必须具有其布局用于扩展 ListFragment 的 Fragment 或扩展 ListActivity 的 Activiy 的 id 另请参阅上一个注释。
  2. 我不知道您为什么在 MainActivity 布局中将列表视图的 id 保留为 android:list 真的需要吗?
  3. 请再次检查所有片段和活动以及应用程序中使用的布局。您可能确实在一个文件夹中更改了 listview 的 id 而离开了其他文件夹,因此您需要在每个 res/layout/ 中进行更改和 res/layout-.../ 该 R.layout.Women_list 的目录

【讨论】:

  • 感谢Shadow的详细回答,我已经添加了您的所有建议,只是想了解如何自定义片段布局。这很混乱
  • @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);新的 LoadInbox().execute();返回根视图; }
  • 如果可能的话,您能否将 R.layout.women_list 添加到问题中...以上解决方案是否有效?
  • 谢谢我添加了 R.layout.women_list XML 和 Main Activity XML,我还用我目前拥有的内容更新了我的代码。非常感谢您的帮助
  • 也许问题是因为我在我的主要活动中扩展了 FragmentActivity。 1.我的代码中只用到了两个listview,@id/android:list只用在PagesFragment xml中,另一个在MainActivity中(android:id="@+id/list") 2.我改了mDrawerList = (ListView) this.findViewById(R.id.list); 3.我检查了所有布局文件夹
猜你喜欢
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多