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