如何在Android中的viewpager的不可见片段中执行一个函数

时间:2012-11-14 10:34:32

标签: android android-asynctask android-fragments

我有两个片段Fragment1和Fragment2.当我启动应用程序时,两个片段中定义的函数都会被执行。因此启动需要很长时间(因为XML解析和列表视图的填充都在两个片段上执行)我需要减少应用程序的启动时间。它们是否可以在启动时执行Fragment1,并且Fragment2的执行带来了后台?这样用户就可以与Fragment1进行交互.Pragment2执行其功能而不会使用户不知情。

这是我的代码,

片段1 =>

    public class Fragment1 extends Fragment{


public static String feedurl="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
static String URL = "";
static final String KEY_HEAD = "item"; // parent node
static final String KEY_DATE = "pubDate";
public static String headflag="";
int f=0;
GridView list;
HeadlinesAdapter adapter;
private TextView mMessageView;
private Button mClearButton;

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

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


    return v;
}

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



    headlines.parse();
    populate_listview();

    }


 public void populate_listview()
 {


     URL="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
     ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml);
    NodeList nl = doc.getElementsByTagName(KEY_HEAD);
    NodeList itemLst = doc.getElementsByTagName("item");
    String MarqueeStr="";

    for (int i = 0; i < nl.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
                    newsList.add(map);


 }
    list=(GridView)getActivity().findViewById(R.id.grid);
    adapter=new Adapter1(getActivity(), newsList);        
            list.setAdapter(adapter);

  }

Fragment2 =&GT;

    public class Fragment2 extends Fragment{


public static String feedurl="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
static String URL = "";
static final String KEY_HEAD = "item"; // parent node
static final String KEY_DATE = "pubDate";
public static String headflag="";
int f=0;
GridView list;
HeadlinesAdapter adapter;
private TextView mMessageView;
private Button mClearButton;

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

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


    return v;
}

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



    sports.parse();
    populate_listview();

    }


 public void populate_listview()
 {


     URL="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
     ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml);
    NodeList nl = doc.getElementsByTagName(KEY_HEAD);
    NodeList itemLst = doc.getElementsByTagName("item");
    String MarqueeStr="";

    for (int i = 0; i < nl.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
                newsList.add(map);


 }
    list=(GridView)getActivity().findViewById(R.id.grid2);
    adapter=new HeadlinesAdapter(getActivity(), newsList);        
            list.setAdapter(adapter);

  }

MainActivity =&GT;

 public class MainActivity extends FragmentActivity {

private ViewPager mViewPager;
private MessageLoader mLoader;
private Button mSenderButton, mReceiverButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // We get UI references
    mViewPager = (ViewPager) findViewById(R.id.viewPager);
    mSenderButton = (Button) findViewById(R.id.sender_button);
    mReceiverButton = (Button) findViewById(R.id.receiver_button);
    // set pager adapter
    mViewPager.setAdapter(new MyAdapter(this));
    // set receiver button listener
    mReceiverButton.setOnClickListener(new OnClickListener() {          

        public void onClick(View v) {
            mViewPager.setCurrentItem(1);
        }
    });

    mSenderButton.setOnClickListener(new OnClickListener() {            

        public void onClick(View v) {
            mViewPager.setCurrentItem(0);
        }
    });
}


private class MyAdapter extends FragmentPagerAdapter{

    private Context mContext;
    private String[] frags = {Fragment1.class.getName(), Fragment2.class.getName()};

    public MyAdapter(FragmentActivity activity) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment frag = (Fragment) super.instantiateItem(container, position);
        if(frag instanceof MessageLoader){
            mLoader = (MessageLoader) frag;
        }
        return frag;
    }

    @Override
    public Fragment getItem(int pos) {
        return Fragment.instantiate(mContext, frags[pos]);
    }

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

}
}

1 个答案:

答案 0 :(得分:1)

这与您的其他问题有关:

  

他们以任何方式在应用程序时停止执行Fragment2   startup.I必须在我滑到Fragment2

时启动它

不,你不应该首先尝试这样做。 ViewPager需要第二个Fragment(尚未显示)才能处于良好状态,以便用户可以选择立即滑动到它。如果不构建Fragment那么用户体验将会很差,特别是在您解析主Url线程上UI的某些xml时。如果你想提高应用程序的速度并避免可能的ANR,你应该真的看看在后台线程上进行xml解析。

  

我想在启动时调用'function1',只在我调用'function2'时调用'function1'   滑动到Fragment2

保持Fragment 1现在(调用您希望调用的方法),然后使用OnPageChangeListener上的ViewPager。我假设您使用自定义FragmentPagerAdapter,因此您可以获得对第二个Fragment的引用,并直接调用populate_listview()方法:

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
      Fragment2 = (Fragment2) getSupportFragmentManager()
                    .findFragmentByTag(
                            "android:switcher:" + R.id.viewPager + ":" + 1);
      if (fragment != null) {
        fragment.populate_listview();// remove the call from onViewCreated
      }
}

但这只是一个黑客。您要做的是使用后台线程(AysncTask或普通线程)进行长时间操作。看看这个blog entry