简体   繁体   中英

Calling functions inside fragments in Android

In my android application Iam using viewpager.I have two fragments.Fragment1 and Fragment2.Iam calling two different function on both fragments.ie, 'function1' on Fragment1 and 'function2' on fragment2.When I start the application, both these two functions are called together.I want to call 'function1' on startup and 'function2' only when I swipe to Fragment2.How can I do this? Thanks in advance.....

Here is my code,

Fragment1=>

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);



        function1();//here I am calling function1
        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=>

   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);



        function2();//here I am calling function2
        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);

      }




}

Main Activity=>

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

    }




}

Here is the layouts,

first_fragment.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="fill_parent"
    android:background="#ffff"
    android:orientation="vertical" >



    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >



    </RelativeLayout>

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="2" >
    </GridView>

</LinearLayout>

second_fragment.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="fill_parent"
    android:background="#ffff"
    android:orientation="vertical" >



    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >



    </RelativeLayout>

    <GridView
        android:id="@+id/grid2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="2" >
    </GridView>

</LinearLayout>

main.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="fill_parent"
    android:orientation="vertical" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#CCCCCC"
        android:gravity="center_vertical"
        android:paddingTop="3dp" >

        <Button
            android:id="@+id/receiver_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Headlines" />

        <Button
            android:id="@+id/sender_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Kerala" />
    </TableRow>

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

You can capture the swipe event by using this code:

mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 
{

}

@Override
public void onPageSelected(int position) {
       if(position==0){
        function1();
       }else if(position==1){
        function2();
       }

}

@Override
public void onPageScrollStateChanged(int state) {

}
});

call your function in any of the best suited overridden method

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