如何多次使用同一个片段?

时间:2016-10-07 03:24:06

标签: java android xml listview android-fragments

我正在创建一个应用程序,该应用程序从网站的XML文件中获取数据并将这些数据传递给Fragment

我使用Action Bar,我有3个标签,还有ViewPager。 该片段包含ListView,我使用Bundle传递数据,我可以正确地从片段中获取传递的数据。

public Fragment getItem(int i){
  switch(i){
    case 0:
      Bundle b1= new Bundle();
      b1.putString("cat", "artufonews");
      Fragment f1 = new LoadFrag();
      f1.setArguments(b1);
      return f1;
    case 1:
      Bundle b2 = new Bundle();
      b2.putString("cat", "artufo");
      Fragment f2 = new LoadFrag();
      f2.setArguments(b2);
      return f2;
    case 2:
      Bundle b3 = new Bundle();
      b3.putString("cat", "artmyst");
      Fragment f3 = new LoadFrag();
      f3.setArguments(b3);
      return f3;
    default :
      return new LoadMee();
  }
}

LoadFrag 是我拥有的片段。我可以正确传递数据,但是当我尝试使用mPager.getAdapter().notifyDataSetChanged()更新列表视图时,无论我做什么,这3个选项卡都会向我显示相同的列表。

下面的代码是片段代码:

public static class LoadFrag extends Fragment{
    String cat;
    boolean kl = false;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        //new TestAsync().execute();
        View rootView = inflater.inflate(R.layout.listfrage, container, false);
        ListView viewer;
        String[] hell = (String[])list.toArray(new String[list.size()]);

        final String[] tots = (String[])links.toArray(new String[links.size()]);
        cat = getArguments().getString("cat");
        CustomLister lister = new CustomLister(getActivity(), hell, bmps);
        viewer = (ListView)rootView.findViewById(R.id.lister);
        viewer.setAdapter(lister);
        viewer.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                Toast.makeText(getActivity(), "You clicked: item " + tots[position], Toast.LENGTH_SHORT).show();;

                Intent i = new Intent(getActivity(), Starter.class);
                i.putExtra("link", tots[position]);
                startActivity(i);
            }
        });
        return rootView;    
    }

    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible && kl == false) {
            getActivity().setTitle(cat);
            new TestAsync().execute();
            kl = true;
        }
    }

    class TestAsync extends AsyncTask<Void, Integer, String>
    {
        String TAG = getClass().getSimpleName();

        ProgressDialog dialog;
        protected void onPreExecute (){
            Log.d(TAG + " PreExceute","On pre Exceute......");

            dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Loading content..");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }

        protected String doInBackground(Void...arg0) {
            Log.d(TAG + " DoINBackGround","On doInBackground...");


            tasker(cat);

            return "You are at PostExecute";
        }

        protected void onProgressUpdate(Integer...a){
            Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
        }

        protected void onPostExecute(String result) {
            Log.d(TAG + " onPostExecute", "" + result);
            dialog.dismiss();
            mPager.getAdapter().notifyDataSetChanged();
    }


    public void tasker(String tag)
    {
        try{
            URL url = new URL("http://www.skyovnis.com/test.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName(tag);



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

                Node node = nodeList.item(i);

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("title");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                list.add(((Node)nameList.item(0)).getNodeValue());

                NodeList websiteList = fstElmnt.getElementsByTagName("link");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                links.add(((Node) websiteList.item(0)).getNodeValue());

                NodeList imgLinks = fstElmnt.getElementsByTagName("linkp");
                Element imgElement = (Element) imgLinks.item(0);
                imgLinks = imgElement.getChildNodes();
                linksp.add(((Node) imgLinks.item(0)).getNodeValue());
            }

            bmps = new Bitmap[linksp.size()];
            String[] imgs = (String[])linksp.toArray(new String[linksp.size()]);
            for(int i = 0; i < linksp.size(); i++){
                URL urls = new URL(imgs[i]);
                bmps[i] = BitmapFactory.decodeStream(urls.openConnection().getInputStream());
            }

            org.jsoup.nodes.Document docs = Jsoup.connect("http://www.skyovnis.com/arecibo-message/").get();
            org.jsoup.select.Elements newsHeadlines =  docs.select("div.entry-content p");

            for(org.jsoup.nodes.Element ele : newsHeadlines){
                hello = hello + ele.text();
            }

        }
            catch(Exception e){
                System.out.println(e);
            }
    }
  }
}

基本上,根据我传递的数据,AsyncTask将运行并从xml文件中读取。我传递给片段的字符串是从xml中查找的标记。所有的东西都有效,除了每个标签都显示同一个列表。

我在这里做错了什么?

编辑

ViewPager适配器

mAdapter = new MyAdapter(getSupportFragmentManager());

mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);

mPager.setOnPageChangeListener(
   new ViewPager.SimpleOnPageChangeListener() {
         @Override
         public void onPageSelected(int position) {
           // When swiping between pages, select the
           // corresponding tab.
           getActionBar().setSelectedNavigationItem(position);
         }
});

我的CustomLister类,

    package com.ovnis.skybeings;

import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomLister extends ArrayAdapter<String>{

    private final Activity context;
    private final String[] web;
    private final Bitmap[] bmps;

    public CustomLister(Activity context, String[] web, Bitmap[] bmps){

        super(context, R.layout.list_compon, web);

        this.context = context;
        this.web = web;
        this.bmps = bmps;
    }

    @Override
    public View getView(int pos, View view, ViewGroup parent){
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.list_compon, null, true);
        TextView txtTitle = (TextView)rowView.findViewById(R.id.txt);

        ImageView imageView = (ImageView)rowView.findViewById(R.id.img);
        txtTitle.setText(web[pos]);

        imageView.setImageBitmap(bmps[pos]);
        return rowView;
    }
}

Myadapter,

public static class MyAdapter extends FragmentPagerAdapter{
    public MyAdapter(FragmentManager fm){
        super(fm);
    }

    @Override
    public int getCount(){
        return tabs.length;
    }

    @Override
    public Fragment getItem(int i){
        switch(i){
        case 0:
            return new LoadMee();
        case 1:
            return new LoadFrag().newInstance("artufonews");
        case 2:
            return new LoadFrag().newInstance("artifos");
            default :
                return new LoadMee();
        }
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

}

2 个答案:

答案 0 :(得分:2)

您需要抓住之前发送过的Bundle。做下面的事情也许可以解决你的问题:

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

  Bundle bundle = this.getArguments();
  if (bundle != null) {
    yourStringData= bundle.getString("cat", "DEFAULT_VALUE");
    setupYourUIWithTheData(yourStringData);
  } else {
      Log.d(TAG, "bundle null");
  }
}

private void setupYourUIWithTheData(String yourData) {
  // Process the received data here.
  // Show all related with the data here.
}

---更新---

要将值传递给Fragment,建议的方法是在您的Fragment添加静态方法,例如:

public static LoadFrag newInstance(String category) {
  LoadFrag fragment = new LoadFrag ();
  Bundle bundle = new Bundle();
  bundle.putString("cat", category);
  fragment.setArguments(bundle);
  return fragment;
}

然后你可以简单地通过以下方式调用它:

LoadFrag.newInstance("your_category");

答案 1 :(得分:1)

出了什么问题:

MyAdapter getItemPosition()方法中,您将返回POSITION_NONE。这意味着无论何时拨打MyAdapter#notifyDataSetChanged(),您都会重新创建ViewPager中的所有片段。您可以通过在LoadFrag#onCreateView()中添加日志消息来验证此行为。

public static class LoadFrag extends Fragment{
    ...
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    // Add a Log message here to verify
    Log.d("LoadFrag", "In onCreateView");

        ...
    }

    ...
}

请注意,每次onCreateView()完成后都会调用AsyncTask。您基本上在LoadFrag完成后重新显示AsyncTask并显示ListView的初始状态。

如何解决

CustomLister中添加一种方法来更新您的数据。

public class CustomLister extends ArrayAdapter<String>{
    ...
    public void updateData(String[] newWeb, Bitmap[] newBmps){
        web = newWeb;
        bmps = newBmps;
        notifyDataSetChanged();
    }
    ...
}

AsyncTask中,获取CustomLister的引用,并使用新的数据集调用lister.updateData(),而不是调用mPager.getAdapter().notifyDataSetChanged()