简体   繁体   中英

How to put a ListView into a Fragment

I'm trying to put a ListView in a fragment, but my app crash. I followed this guide to learn how to put a ListView in an activity, but I want to put it in a fragment so I changed the code a bit. This is my fragment:

public class FaqFragment extends Fragment {

public static Fragment newInstance() {
    FaqFragment fragment = new FaqFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

private ListView listView1;

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

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

    Element element_data[] = new Element[]
    {
        new Element(R.drawable.goccia, "Goccia1"),
        new Element(R.drawable.goccia, "Goccia2"),
        new Element(R.drawable.goccia, "Goccia3"),
        new Element(R.drawable.goccia, "Goccia4"),
        new Element(R.drawable.goccia, "Goccia5")
    };

    ElementAdapter adapter = new ElementAdapter(getActivity(), android.R.layout.simple_list_item_1, element_data);


    listView1 = (ListView)v.findViewById(R.id.listView1);

    View header = (View)getLayoutInflater(savedInstanceState).inflate(R.layout.element, null);
    listView1.addHeaderView(header);

    listView1.setAdapter(adapter);

    return v;
}

This is my ArrayAdapter :

public class ElementAdapter extends ArrayAdapter<Element>{

FragmentActivity context; 
int layoutResourceId;    
Element data[] = null;

public ElementAdapter(FragmentActivity fragmentActivity, int layoutResourceId, Element[] data) {
    super(fragmentActivity, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = fragmentActivity;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    WeatherHolder holder = null;

    if(row == null)
    {
        LayoutInflater inflater = ((FragmentActivity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new WeatherHolder();
        holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
        holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

        row.setTag(holder);
    }
    else
    {
        holder = (WeatherHolder)row.getTag();
    }

    Element element = data[position];
    holder.txtTitle.setText(element.title);
    holder.imgIcon.setImageResource(element.icon);

    return row;
}

static class WeatherHolder
{
    ImageView imgIcon;
    TextView txtTitle;
}

}

And this is my Element :

public class Element {
public int icon;
public String title;
public Element(){
    super();
}

public Element(int icon, String title) {
    super();
    this.icon = icon;
    this.title = title;
}

}

The app has 3 tabs, the app crash when I swipe to the tab where is the code that I've already wrote (fragment).

In the logcat there is this error:

03-13 11:25:39.455: E/AndroidRuntime(2840): at com.example.bluhackathon.ElementAdapter.getView(ElementAdapter.java:47)

I tried to delete lines 47, 48 and 49 of the ArrayAdapter and the app didn't crash (of course there was a list with empty elements.

Lines 47, 48, 49:

Element element = data[position];
    holder.txtTitle.setText(element.title);
    holder.imgIcon.setImageResource(element.icon);

you can use ListFragment to implement it, below is my answer to implement "put a listview into a Fragment, and get the data from MySQL", i wrote it yesterday and hope it can help you solve the problem.

    package com.ecnu.vendingmachine;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.ecnu.vendingmachine.widgets.JSONParser;

public class VendingFragment extends ListFragment {

    private String Tag = "VendingFragment";
    private static final String TAG_SUCCESS = "success";

    private ListView listView;

    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    JSONArray vendingmachine = null;

    ArrayList<HashMap<String, String>> vendinglist;

    // url to get all products list
    MainActivity main = new MainActivity();
    private String url_all_vendingmachine = main.getIP()
            + "vendingmachine/get_all_vendingmachine.php";

    // products JSONArray

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

        return inflater.inflate(R.layout.vending_main, container, false);
    }

     @Override 
     public void onViewCreated (View view, Bundle savedInstanceState) {

        vendinglist = new ArrayList<HashMap<String, String>>();
        //listView = (ListView) view.findViewById(R.id.list);

        listView = getListView();
        new get_all_vendingmachine().execute();
    }   

    class get_all_vendingmachine extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            Log.i(Tag, "pDialog");
        }

        protected String doInBackground(String... args) {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            Log.i(Tag, url_all_vendingmachine);
            // getting JSON Object
            // Note that create product url accepts POST method

            JSONObject json = jsonParser.makeHttpRequest(
                    url_all_vendingmachine, "GET", params);

            // check log cat for response
            Log.i(Tag, json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // Ada record Data (SUCCESS = 1)
                    // Getting Array of vendingmachine
                    vendingmachine = json.getJSONArray("vendings");

                    // looping through All vendingmachine
                    for (int i = 0; i < vendingmachine.length(); i++) {
                        JSONObject c = vendingmachine.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString("VMid");
                        String name = c.getString("Name");
                        String address = c.getString("Address");
                        Log.i(Tag, id);
                        Log.i(Tag, name);
                        Log.i(Tag, address);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put("VMid", id);
                        map.put("Name", name);
                        map.put("Address", address);

                        // adding HashList to ArrayList
                        vendinglist.add(map);
                    }

                } else {
                    // failed to create product
                    getActivity().finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // updating listview
                    // HashMap<String, String>中的key
                    String[] from = { "Name", "Address", "VMid" };
                    // list_item.xml中对应的控件ID
                    int[] to = { R.id.vending_name, R.id.vending_address,
                            R.id.vending_id };
                    Log.i(Tag, from[0]);
                    SimpleAdapter adapter = new SimpleAdapter(getActivity(),
                            vendinglist, R.layout.vending_list, from, to);
                    listView.setAdapter(adapter);
                }
            });
        }

    }

}

the vending_main_xml:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/whiteColor" >

    <include
        android:id="@+id/layout_buy_title_actionbar"
        layout="@layout/headbar_title" />

    <ListView
        android:id="@id/android:list"
        android:layout_below="@id/layout_buy_title_actionbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="@android:color/transparent"
        android:divider="@drawable/reader_item_divider"
        android:listSelector="@android:color/transparent" >
    </ListView>

</RelativeLayout>

the vending_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="@dimen/selectVmListCell_Height"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="@dimen/selectVmListCell_Height"
        android:layout_gravity="center_vertical"
        android:background="@drawable/bg_listview"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/layout_Margin_10" >

        <LinearLayout
            android:id="@+id/imageTypeLayout"
            android:layout_width="@dimen/smallImage_HW_45"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/vendingImage"
                style="@style/smallImageStyle"
                android:src="@drawable/buy_main_not_shop" />

            <TextView
                android:id="@+id/distanceText"
                style="@style/smallTxtStyle"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:singleLine="true"
                android:textColor="@color/lightOrangeColor" />
        </LinearLayout>

        <RelativeLayout
            android:id="@+id/vendingSave"
            android:layout_width="47.0dip"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" >

            <ImageView
                android:id="@+id/vendingSaveImage"
                android:layout_width="27.0dip"
                android:layout_height="27.0dip"
                android:layout_centerInParent="true"
                android:layout_centerVertical="true"
                android:background="@drawable/bg_favor_btn" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/layout_Margin_10"
            android:layout_toLeftOf="@id/vendingSave"
            android:layout_toRightOf="@id/imageTypeLayout"
            android:gravity="center_vertical"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/vending_name"
                style="@style/midDarkGrayTxtStyle"
                android:layout_width="fill_parent" />

            <TextView
                android:id="@+id/vending_address"
                style="@style/smallLightGrayTxtStyle"
                android:layout_width="fill_parent"
                android:maxLines="2" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <TextView
                    style="@style/smallLightGrayTxtStyle"
                    android:text="Number:" />

                <TextView
                    android:id="@+id/vending_id"
                    style="@style/smallLightGrayTxtStyle" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

hope it can help you to find how to put the listview into a fragment. the element in my listview is complex, if you just want a single row, it's more simple than what i code.

尝试使用ListFragment,或者您可以从vogella遵循指南

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM