0

我有这个应用程序,我在其中实现了 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);

    }
  }

}

精选列表适配器:

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;
}
4

2 回答 2

1

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

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

于 2012-07-03T07:31:28.793 回答
0

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

在启动 asyncTask 之前清除 projectList 或检查列表是否包含一些数据,并基于此调用执行 asyncTask(如果列表为空或不包含任何元素)。

于 2012-07-03T09:24:05.970 回答