在ViewPager中为特定片段添加按钮

时间:2013-03-20 20:38:04

标签: android android-fragments android-viewpager android-pageradapter

我在android SDK中找到了ViewPager并且正在搞乱它。基本上我的最后一项任务是在一个应用程序中创建一个youtube,facebook和twitter feed,使用ViewPager和Fragments在3个类别之间滚动。我在理解这些工作时遇到了一些困难,更具体地说,我如何在特定的片段中添加一个元素(Button)?到目前为止,这是我的代码:

package com.ito.mindtrekkers;

import java.util.ArrayList;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("ShowToast")

//Brady Mahar

public class Main extends FragmentActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    ArrayList<String> tweetList = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setCurrentItem(1); //sets initial page to "Facebook"
        new DownloadFilesTask().execute("weather" , null, null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.title_youtube);
            case 1:
                return getString(R.string.title_facebook);
            case 2:
                return getString(R.string.title_twitter);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @SuppressLint("ShowToast")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // Create a new TextView and set its text to the fragment's section
            // number argument value.
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));






            return textView;
        }
    }

    /**
     * Class for handling NetworkOnMainThread
     * Sends the command Asynchronously 
     * @author austinn
     *
     */
    private class DownloadFilesTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... command) {

            Twitter twitter = new TwitterFactory().getInstance();
            Query query = new Query("from:MindTrekkers");
            query.setRpp(100);
            try {
                QueryResult result = twitter.search(query);
                for(twitter4j.Tweet tweet : result.getTweets()) {
                    //Toast.makeText(getApplicationContext(), tweet.getText(), Toast.LENGTH_SHORT);
                    Log.v("Tweet", tweet.getText());
                    tweetList.add(tweet.getText());
                }
            } catch (TwitterException e) {
                //Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_SHORT);
                Log.v("Error", e+"");
            }

            return null;
        }

        protected void onProgressUpdate(Void... progress) {}
        protected void onPostExecute(String result) {}
    }


}

2 个答案:

答案 0 :(得分:1)

使用Singleton实例getter在单独的Fragment类中实现3个Fragment类别(youtube,facebook和twitter)。这是一个Facebook Fragment示例(请注意onCreateView()会扩展fragment_facebook布局):

public class FaceBookFragment extends Fragment {
    private static FaceBookFragment instance = null;
    public static FaceBookFragment newInstance() {
        if(instance == null) {
            instance = new FaceBookFragment();
            Bundle args = new Bundle();
            instance.setArguments(args);
            return instance;
        }
        return instance;
    }

    public FaceBookFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_facebook, container,
                false);
        ...
        return rootView;
    }
}

然后在FragmentPagerAdapter(位于上面代码的MainActivity中)中,让getItem()返回Fragment实例:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment frag = null;
        switch (position) {
        case 0:
            frag = FaceBookFragment.newInstance();
            break;
        case 1:
            frag = TwitterFragment.newInstance();
            break;
        case 2:
            frag = YouTubeFragment.newInstance();
            break;
        }
        return frag;
    }
}

BONUS:此外,我知道您的代码是实验性的,但您的推文列表无法从任何片段中访问。

片段是一个新的类对象,除非您在构建期间(限制)传递对象(推文列表)的引用,否则无法直接访问MainActivity中的任何内容,或者获得最终的&#39 ;如果Fragment代码在MainActivity下,则在一个对象/变量上(该列表永远不会从Fragment的角度改变)。 也许我没有说明这个陈述以及其他可能的内容,但是你的片段不能直接访问推文列表。

有几个解决方案:

  1. 将推文列表移至Twitter片段并让其调用下载器。然后你的TwitterFragment可以构建并保存列表并根据需要更新UI。但是,请考虑片段生命周期(http://developer.android.com/guide/components/fragments.html),请参阅生命周期部分和图表。当您滑动/翻转几个片段并再次返回时,将调用onDestroyView()方法。例如Android不会保留无限数量的Fragment,并会根据需要销毁/重新创建视图。不要尝试从AsyncTask更新Fragment的UI /布局对象。在任务完成之前,Fragment可能会调用onDestoryView()。 (你可能会得到NullPointerExceptions)而是让你的AsyncTask只更新Fragment范围变量(tweetlist)并让你的onCreateView()使用同一个变量。 (也许同步变量)

  2. 保持主要变量/对象/ AsyncTask调用代码,全部在MainActivity中,并添加从Fragment访问它们的方法,并使用Fragment getActivity()并将其强制转换为MainActivity并在需要时调用该方法:

    public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
            ArrayList<String> tweetList = new ArrayList<String>();
            ...
            public ArrayList<String> getTweetlist() {
                    return tweetlist;
            }
            ...
    }
    
    public class TwitterFragment extends Fragment {
            ...
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                    View rootView = inflater.inflate(R.layout.fragment_twitter, container, false);
                    ...
                    ArrayList<String> tweetList = ((MainActivity)getActivity()).getTweetlist();
                    ...
                    return rootView;
            }
            ...
    }
    

答案 1 :(得分:0)

让我试着解释一下,首先使用这个FragmentPagerAdapter:

public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
    protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
    protected static final int[] ICONS = new int[] {
            R.drawable.perm_group_calendar,
            R.drawable.perm_group_camera,
            R.drawable.perm_group_device_alarms,
    };

    private int mCount = CONTENT.length;

    public TestFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {Fragment f = null;
    switch(position){
    case 0:
    {
    f = new ArrayListFragment();//YourFragment
    // set arguments here, if required
    Bundle args = new Bundle();
    f.setArguments(args);
    break;
    }
    case 1:
    {
        f = new HomeFragment();//YourFragment
        // set arguments here, if required
        Bundle args = new Bundle();
        f.setArguments(args);
        break;
    }
    case 2:
    {   
        f = new EndlessCustomView();//YourFragment
        // set arguments here, if required
        Bundle args = new Bundle();
        f.setArguments(args);
        break;
    }   
    default:
      throw new IllegalArgumentException("not this many fragments: " + position);
    }


    return f;
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      return TestFragmentAdapter.CONTENT[position % CONTENT.length];
    }



    @Override
    public int getIconResId(int index) {
      return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}

如您所见,ArrayListFragment,HomeFragment和EndlessCustomView是一个扩展Fragment的类,因此对于onCreate()中的每个类,您可以设置SetContentView(R.layout.your_layout);

然后您可以在此布局中添加按钮或任何您想要的内容。