Android ListFragment重复条目

时间:2012-07-03 07:25:27

标签: android fragment listadapter android-listfragment

我有这个应用程序,我实现了ActionBar Fragment接口。在接口的基础上,有一个ListFragment,每次切换到不同的选项卡时,列表中的条目都会保持重复。有人能告诉我使用自定义适配器实现listfragment的正确方法吗?

以下是我的代码: FeaturedFragment.java

public class FeaturedFragment extends ListFragment {

static final String URL = "http://www.sundancepost.com/ivue/Featured.xml";

static final String KEY_PROJECT = "project"; // parent node
static final String KEY_BANNER = "banner";

ListView featuredList;
FeaturedListAdapter featuredAdapter;
ArrayList<HashMap<String, String>> projectsList = new ArrayList<HashMap<String, String>>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.featured_list, container, false);
        featuredList = (ListView)view.findViewById(android.R.id.list);

        return view;
 }

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

        ConnectivityManager cMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
         if (cMgr.getActiveNetworkInfo() != null && cMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {

            new MyAsyncTask().execute();

          } else {
             AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
             builder.setMessage("Please check your internet connection");
             builder.setTitle("Failed to download resources");
             builder.setCancelable(false);
             builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           return;
                       }
                   });
                AlertDialog alert = builder.create();
                alert.show();
        }

    featuredAdapter = new FeaturedListAdapter(getActivity(), projectsList);

}

public class MyAsyncTask extends AsyncTask<Void,Void,Void>{

    private final ProgressDialog recents_dialog = new ProgressDialog(getActivity());

    @Override
    protected Void doInBackground(Void... params) {

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL);
        Document doc = parser.getDomElement(xml);

        NodeList nl = doc.getElementsByTagName(KEY_PROJECT);

        for (int i = 0; i < nl.getLength(); i++) {

            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);

            map.put(KEY_BANNER, parser.getValue(e, KEY_BANNER));

            projectsList.add(map);
        }
        return null;
    }

    @Override
    protected void onPreExecute()
    {
        recents_dialog.setMessage("Loading ...");
        recents_dialog.show();
        recents_dialog.setCancelable(false);
    }

    @Override
    protected void onPostExecute(Void result)
    {
        if(recents_dialog.isShowing() == true)
        {
            recents_dialog.dismiss();
        }
         // Getting adapter by passing xml data ArrayList

        featuredList.setAdapter(featuredAdapter);

    }
  }

}

FeaturedListAdapter:

public class FeaturedListAdapter extends BaseAdapter {

private Activity activity;
ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public FeaturedListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data= (ArrayList<HashMap<String, String>>) d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

        View vi = convertView;

        if(vi==null){
            vi=new View(activity);
            vi = inflater.inflate(R.layout.featured_listrow, null);
        }

        ImageView banner =(ImageView)vi.findViewById(R.id.banner); // thumb image
        banner.setAdjustViewBounds(true);
        imageLoader.DisplayImage(data.get(position).get(FeaturedFragment.KEY_BANNER), banner);

        return vi;
  }
}

[编辑] 根据@ 10s的建议修改以下代码。但是,结果仍然相同..

public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.featured_listrow, null);
            holder = new ViewHolder();
            holder.banner = (ImageView)convertView.findViewById(R.id.banner);
            holder.banner.setAdjustViewBounds(true);
            imageLoader.DisplayImage(data.get(position).get(FeaturedFragment.KEY_BANNER), holder.banner);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        return convertView;
}

public static class ViewHolder {
    public ImageView banner;
}

2 个答案:

答案 0 :(得分:1)

您在Custom适配器的getView()中使用的代码每次调用时都会重新创建视图。每当您的案例片段中的活动成为焦点时,适配器就会重新呈现自己。

尝试使用适配器的支架。这是Android最佳实践,非常简单实用。帮助您入门的链接:http://android.amberfog.com/?p=296

答案 1 :(得分:0)

每次切换选项卡时添加重复条目的原因是,每次切换到此选项卡时,都会调用onActivityCreated()方法。因此你的AsyncTask每次执行,并且在AsyncTask的doInBackground()方法中,你继续将你的元素添加到projectList arraylist而不清除它。

在启动asyncTask之前清除projectList或检查列表是否包含某些数据,并根据它调用执行asyncTask(如果list为null或不包含任何元素)。