如何将列表视图放在片段中

Posted

技术标签:

【中文标题】如何将列表视图放在片段中【英文标题】:How to put listview inside a fragment 【发布时间】:2013-03-09 14:10:10 【问题描述】:

如何将列表视图放入片段中?我使用带有固定选项卡的默认项目设置。

它似乎不起作用,我的应用程序崩溃了。

主要活动

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.app.ListFragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener 
    /**
     * The @link android.support.v4.view.PagerAdapter that will provide
     * fragments for each of the sections. We use a
     * @link android.support.v4.app.FragmentPagerAdapter derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * @link android.support.v4.app.FragmentStatePagerAdapter.
     */

    /**
     * The @link ViewPager that will host the section contents.
     */
    ViewPager mViewPager;
    public final static String PREFS_NAME = "UserData";
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        //Only for safe mode 
        StrictMode.ThreadPolicy policy = new StrictMode.
        ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        /***********************************USER***************************/
        //Get User info (if exist)
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String id = settings.getString("id", "");
        String pass = settings.getString("pass", "");
        SectionsPagerAdapter mSectionsPagerAdapter;
        //Else create New User
        if (id == "")
        
            System.out.println("Create New User...");
            UserRegistration.CreateUser(getApplicationContext());
        
        /**** OTHER*****/
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
                    @Override
                    public void onPageSelected(int position) 
                        actionBar.setSelectedNavigationItem(position);
                    
                );

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) 
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        


    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) 
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) 
    

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) 
    

    /**
     * A @link FragmentPagerAdapter that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter 

        public SectionsPagerAdapter(FragmentManager fm) 
            super(fm);
        

        @Override
        public Fragment getItem(int position) 
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        

        @Override
        public int getCount() 
            // Show 5 total pages.
            return 5;
        

        @Override
        public CharSequence getPageTitle(int position) 
            Locale l = Locale.getDefault();
            switch (position) 
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            case 3:
                return getString(R.string.title_section4).toUpperCase(l);
            case 4:
                return getString(R.string.title_section5).toUpperCase(l);   
            
            return null;
        
    

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment 
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() 
        

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) 


            View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);       
            /***********************************CONTEST INC**********************
            String xmlURL;
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
            xmlURL = URL;
            System.out.println("Case 1");
            Document doc = XMLfunctions.XMLfromString(XMLfunctions.getXML(xmlURL));
            NodeList nodes = doc.getElementsByTagName("contest");
            for (int i = 0; i < nodes.getLength(); i++) 
                                       
                HashMap<String, String> map = new HashMap<String, String>();    

                Element e = (Element)nodes.item(i);
                map.put("id", XMLfunctions.getValue(e, "id"));
                map.put("name", XMLfunctions.getValue(e, "name"));
                map.put("subtitle",XMLfunctions.getValue(e, "subtitle"));
                mylist.add(map);
                System.out.println(mylist);
            
            //new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, android.R.id.text1, actions);

            ListAdapter adapter = new SimpleAdapter(this.getActivity(), mylist , R.layout.contest_list, 
                    new String[]  "name", "subtitle" , 
                    new int[]  R.id.item_title, R.id.item_subtitle );

            ListFragment.setListAdapter(adapter);

            final ListView lv = getApplication().getActivity().getListView();
            lv.setTextFilterEnabled(true);  
            lv.setOnItemClickListener(new OnItemClickListener() 
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)               
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                    Toast.makeText(this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

                
            );



            /*************************************END CONTEST*********************/
            ContestList.GetList(getActivity(), 1, "mm", "njk");

            //TextView dummyTextView = (TextView) rootView
                //  .findViewById(R.id.section_label);
            String sectionNumb = Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER));
            int cat1;
            cat1 = Integer.parseInt(sectionNumb); 
            switch (cat1)
            
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;
               
            return rootView;
        
    

竞赛列表类

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ContestList 
    public final static String PREFS_NAME = "UserData";

    public static String GetList(Context context, int type, String id, String pass)
    

        String xmlURL;
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        xmlURL = URL;
        System.out.println("Case 1");
        Document doc = XMLfunctions.XMLfromString(XMLfunctions.getXML(xmlURL));
        NodeList nodes = doc.getElementsByTagName("contest");
        for (int i = 0; i < nodes.getLength(); i++) 
                                   
            HashMap<String, String> map = new HashMap<String, String>();    

            Element e = (Element)nodes.item(i);
            map.put("id", XMLfunctions.getValue(e, "id"));
            map.put("name", XMLfunctions.getValue(e, "name"));
            map.put("subtitle",XMLfunctions.getValue(e, "subtitle"));
            mylist.add(map);
            System.out.println(mylist);
        
        //new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, android.R.id.text1, actions);

        ListAdapter adapter = new SimpleAdapter(context, mylist , R.layout.contest_list, 
                new String[]  "name", "subtitle" , 
                new int[]  R.id.item_title, R.id.item_subtitle );

        ((ListActivity) context).setListAdapter(adapter);

        final ListView lv = ((ListActivity) context).getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() 
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)               
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                //Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

            
        );
        return "OK";
       
    public String adapter(ListAdapter adapter)
    /*
        setListAdapter(adapter);

        final ListView lv = getApplication().getActivity().getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() 
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)               
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(MainActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

            
        );*/
        return "OK";
    

activity_main 布局:

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_
    android:layout_
    tools:context=".MainActivity" />

Fragment_main_dummy 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_
android:layout_>    

<ListView
    android:id="@id/android:list"
    android:layout_
    android:layout_
    android:layout_weight="1"
    android:drawSelectorOnTop="false" />

<TextView
    android:id="@id/android:empty"
    android:layout_
    android:layout_
    android:text="No data"/>

<TextView  
android:id="@+id/item_title"
android:layout_ 
android:layout_ 
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="2dp"
android:textSize="20dp" />
<TextView  
android:id="@+id/item_subtitle"
android:layout_ 
android:layout_ 
android:padding="2dp"
android:textSize="13dp" />

有人知道我的应用为什么会崩溃吗?或者有其他方法可以将列表视图放在片段中?

谢谢

编辑:

错误日志

03-20 12:53:31.219: E/AndroidRuntime(3104): FATAL EXCEPTION: main
03-20 12:53:31.219: E/AndroidRuntime(3104): java.lang.ClassCastException: com.time2win.MainActivity cannot be cast to android.app.ListActivity
03-20 12:53:31.219: E/AndroidRuntime(3104):     at com.time2win.ContestList.GetList(ContestList.java:50)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at com.time2win.MainActivity$DummySectionFragment.onCreateView(MainActivity.java:241)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1012)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.view.ViewPager.populate(ViewPager.java:881)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1366)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.Choreographer.doFrame(Choreographer.java:532)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.os.Handler.handleCallback(Handler.java:725)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.os.Looper.loop(Looper.java:137)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at android.app.ActivityThread.main(ActivityThread.java:5039)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at java.lang.reflect.Method.invokeNative(Native Method)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at java.lang.reflect.Method.invoke(Method.java:511)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 12:53:31.219: E/AndroidRuntime(3104):     at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

你能发布崩溃的堆栈跟踪吗? 【参考方案1】:

您可以为此使用 ListFragment。文档中对此进行了很好的解释:

http://developer.android.com/reference/android/app/ListFragment.html

Vogela 也有这方面的教程:

http://www.vogella.com/articles/AndroidListView/article.html#listfragments

【讨论】:

【参考方案2】:

我得到了输出!!

public class TopRatedFragment extends Fragment 

private String[] mNames =  "F***", "Carlos", "Alex", "Andrea", "Karla",
       "Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
       "Edelmira", "Andres" ;

private String[] mAnimals =  "Perro", "Gato", "Oveja", "Elefante", "Pez",
        "Nicuro", "Bocachico", "Chucha", "Curie", "Raton", "Aguila",
        "Leon", "Jirafa" ;

int[] flags = new int[]
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher,
        R.drawable.ic_launcher  
;


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 

List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

for(int i=0;i<10;i++)
    HashMap<String, String> hm = new HashMap<String,String>();
    hm.put("txt", "App Name : " + mNames[i]);
    hm.put("cur","creator : " + mAnimals[i]);
    hm.put("flag", Integer.toString(flags[i]) ); 
    aList.add(hm);        

String[] from =  "flag","txt","cur" ;

int[] to =  R.id.flag,R.id.txt,R.id.cur,R.id.textView2; 

View v = inflater.inflate(R.layout.fragment_top_rated, container,false);
    ListView list = (ListView)v.findViewById(R.id.listView1);
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);       
    list.setAdapter(adapter);
return v;
 
 

listview_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="horizontal">

<ImageView 
        android:id="@+id/flag"
        android:layout_
        android:layout_
        android:contentDescription="@string/hello_world"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp" />

    <LinearLayout 
        android:layout_
        android:layout_
        android:orientation="vertical" >    

        <TextView 
            android:id="@+id/txt"
            android:layout_
            android:layout_
            android:textSize="15dp" />          

        <TextView 
            android:id="@+id/cur"
            android:layout_
            android:layout_
            android:textSize="10dp" />

</LinearLayout>

</LinearLayout>

fragment_top_rated.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_
    android:layout_
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
</ListView>

</RelativeLayout>

【讨论】:

【参考方案3】:

包含 3 个元素的列表视图的片段示例。关键是onCreateView,别忘了给fragment.xml(fragment_list)充气,在这个里面会有一个listView,里面是“listView$fragment_list$lista”

    public class FragmentList extends Fragment 

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup   container,BundlesavedInstanceState) 

    View v = inflater.inflate(R.layout.fragment_list, container, false);

    ListView lstItems = (ListView)v.findViewById(R.id.listView$fragment_list$lista);

    ArrayList<String> prueba = new ArrayList<String>();
    prueba.add("Element1");
    prueba.add("Element2");
    prueba.add("Element3");

    ArrayAdapter<String> allItemsAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_1,prueba);

    lstItems.setAdapter(allItemsAdapter);

    return v;

【讨论】:

【参考方案4】:

您遇到的错误是由于尝试设置主要活动的列表适配器而不是列表。

在您的竞赛列表类中,您执行以下操作:

((ListActivity) context).setListAdapter(adapter);

但上下文不是针对 ListActivity,而是针对 MainActivity。

你这样做是这样的:

ContestList.GetList(getActivity(), 1, "mm", "njk");

但是 getActivity() 意味着它返回的主要活动是“MainActivity”。你应该改变一些东西来传递列表视图而不是活动上下文,或者找到另一种方式来传递你需要的数据。

【讨论】:

以上是关于如何将列表视图放在片段中的主要内容,如果未能解决你的问题,请参考以下文章

如何将可扩展列表视图的选定子视图数据从片段发送到父活动?

不要在片段中显示列表视图项

如何在片段中填充列表视图?

如何刷新片段上的列表视图

如何从片段内的列表视图打开链接网址?

如何在片段类的列表视图中显示 SQLite 数据库?