2013-09-08 4 views
2

Я не могу найти способ предоставить другой текст динамически созданному фрагменту для моего приложения, защищенного просмотром страниц. Я дошел до того, что завязал, где я застрял. Для моего приложения я хочу иметь 400-500 динамически созданных фрагментов, где вы можете горизонтально перемещаться по ним, а каждое содержимое фрагмента должно быть одинаковым (повторяя один и тот же фрагмент), и единственное, что может быть в тексте на них. Вот где я застрял в моем codding:Как передать различные строки динамически созданным фрагментам с помощью ViewPager?

package com.example.testarearg; 

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.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

public class MainActivity 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; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
     }  

    }); 
} 




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


} 

/** 
* 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. 
    */ private String mText; // display this text in your fragment 

    public static Fragment getInstance(String text) { 
     Fragment f = new Fragment(); 
     Bundle args = new Bundle(); 
     args.putString("text", text); 
     f.setArguments(args); 
     return f; 
    } 

    public void onCreate(Bundle state) { 
     super.onCreate(state); 
     setmText(getArguments().getString("text")); 
     // rest of your code 
    } 

    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public DummySectionFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false); 
     TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label); 
     dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); 
     return rootView; 
    } 

    public String getmText() { 
     return mText; 
    } 

    public void setmText(String mText) { 
     this.mText = mText; 
    } 
} 

} 
+0

Возможный дубликат http://stackoverflow.com/questions/8785221/retrieve-a-fragment-from-a-viewpager – Triode

ответ

2

Вы должны создать свой собственный пользовательский фрагмент:

import android.support.v4.app.Fragment; 

public class YourFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.your_fragment_layout, container, false); 

     TextView tv = (TextView) v.findViewById(R.id.yourtextview); 
     tv.setText(getArguments().getString("text")); 

     return v; 
    } 

    public static YourFragment newInstance(String text) { 

     YourFragment f = new YourFragment(); 
     Bundle b = new Bundle(); 
     b.putString("text", text); 

     f.setArguments(b); 

     return f; 
    } 
} 

А затем измените адаптер. Основная идея заключается в том, что адаптер содержит строки, которые вы хотите отобразить и the getItem(...) метод выберет текст.

public class MyPagerAdapter extends FragmentPagerAdapter { 

     private String [] strings; 

     public MyPagerAdapter(FragmentManager fm, String [] stringstodisplay) { 
      super(fm); 
      this.strings = stringstodisplay; 
     } 

     @Override 
     public Fragment getItem(int pos) { 
      return YourFragment.newInstance(strings[pos]); 
     } 

     @Override 
     public int getCount() { 
      return 500; // or strings.length to be save 
     }  
    } 

От вашей деятельности, вы передаете массив строк, содержащий различные строки к адаптеру.

public class MainActivity extends FragmentActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main);  

     // get the content that your fragments will display 
     String [] strings = new String[500]; 

     for(int i = 0; i < 500; i++) { 
      strings[i] = "This is Fragment " + i; 
     } 

     ViewPager pager = (ViewPager) findViewById(R.id.viewPager); 
     pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), strings)); 
    } 
} 
+0

Я вижу, так что в основном фиктивные один из обсуждения и может быть удалена и тот, который будет использоваться как «ваш фрагментарный»? Кроме того, мне нужно заменить «красный» текст «» или stringstodisplay на мой массив строк? Или где мне нужно ввести строковый массив? Смущенно. Прошу прощения за утечку знаний, сэр. –

+1

Да, вы создаете свой собственный фрагмент, назовите его, как хотите, создайте свой собственный файл макета для фрагмента и надуйте его внутри метода onCreateView (...). Затем, где-то в вашей деятельности вам нужно передать массив строк, который ваши фрагменты должны отображать на адаптер. Я добавил несколько примеров кода. –

+0

Я вижу, спасибо! –

Смежные вопросы