0

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

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


} 

回答

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是扩展片段一类,所以这些类中的每个类都在onCreate()中,你可以通过setContentView(R.layout.your_layout);

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

1

使用Singleton实例获取器在单独的Fragment类中实现3片段类别(youtube,facebook和twitter)。下面是一个Facebook的片段例子(注意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()返回的片段实例:

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

奖金:另外,我知道你的代码是实验性的,但你的tweetlist不会从您的任何片段的访问。

片段是一个新的类对象,除非在构造(限制)过程中传递对象(tweetlist)的引用,否则无法直接访问MainActivity中的任何内容,或者获取对象/变量的'final'如果片段代码在MainActivity下(该列表永远不会从片段的角度改变)。 也许我没有说明这个陈述以及其他的可能,但tweetlist将无法从您的片段访问,因为它是。

有一对夫妇的解决方案:

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

  2. 保持您的主要变量/对象/ AsyncTask调用代码,所有在MainActivity中,并添加方法从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; 
         } 
         ... 
    }