0

I found the ViewPager in the android SDK and was messing around with it. Basically my final task is to create a youtube, facebook, and twitter feed all in one app, using the ViewPager and Fragments to scroll between the 3 categories. I'm having a bit of a hard time understanding house these work, more specifically, how to I add an element (Button) to a specific Fragment? Here's my code so far:

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) {}
    }


}
4

2 回答 2

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

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

Fragment 是一个新的类对象,不能直接访问 MainActivity 中的任何内容,除非您在构造(限制)期间传递对对象(推文列表)的引用,或者如果 Fragment 代码获得对象/变量的“最终”在 MainActivity 下(从 Fragment 的角度来看,列表永远不会改变)。也许我没有像其他人那样清楚地表达这个声明,但是推特列表将无法从您的片段中访问。

有几个解决方案:

  1. 将 tweetlist 移动到 Twitter Fragment 并让它调用下载器。然后您的 TwitterFragment 可以构建并保存列表并根据需要更新 UI。但是,请考虑片段生命周期(http://developer.android.com/guide/components/fragments.html),请参阅生命周期部分和图表) onDestroyView() 方法将在您滑动/翻转几个片段并再次返回时被调用。例如,Android 不会保持无限数量的 Fragment 处于活动状态,并且会根据需要销毁/重新创建视图。不要尝试从 AsyncTask 更新 Fragment 的 UI/布局对象。Fragment 可能会在您的任务完成之前调用 onDestoryView() 。(然后你可能会得到 NullPointerExceptions)而是让你的 AsyncTask 只更新片段范围变量(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;
            }
            ...
    }
    
于 2014-06-23T14:32:21.727 回答
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);

然后你可以在这个布局中添加一个按钮或任何你想要的东西。

于 2013-03-24T03:05:54.423 回答