ViewPager inside Listview for all the rows - android

My main objective is to create a listview, in each row a viewpager with a "ImageWordFragment" in each page, which cotains an Imageview.
Please DON'T tell me not to use viewpager inside a listview. A lots of apps are doing it, just help get to my goal.
I tried setting "setId()" but it prompts a null exception in the ViewPager variable inside the "getView" function.
The problem is the the first viewpager works in the first row of the listview. But the rest of it doesn't.
This is the xml of "fragment_word_image.xml":
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="LALA"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_grey"/>
</LinearLayout>
This is the xml of "item_word.xml":
<LinearLayout
android:id="#+id/moreInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
This is the adapter:
public class WordAdapter extends BaseAdapter {
private AppCompatActivity activity;
private LayoutInflater inflater;
private List<Word> wordItems;
public WordAdapter(AppCompatActivity activity, List<Word> wordItems) {
this.activity = activity;
this.wordItems = wordItems;
}
#Override
public int getCount() {
return wordItems.size();
}
#Override
public Word getItem(int position) {
return wordItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_word, parent, false);
}
FrameLayout container = (FrameLayout) convertView.findViewById(R.id.container);
TextView type = (TextView) convertView.findViewById(R.id.type);
TextView name = (TextView) convertView.findViewById(R.id.name);
ImageView progress = (ImageView) convertView.findViewById(R.id.progress);
final LinearLayout moreInfo = (LinearLayout) container.findViewById(R.id.moreInfo);
ViewPager pager = (ViewPager) convertView.findViewById(R.id.viewPager);
// Getting word data
final Word w = wordItems.get(position);
//Pager
WordPagerAdapter adapter = new WordPagerAdapter(activity.getSupportFragmentManager(), activity, pager);
Bundle args1 = new Bundle();
args1.putString(ImageWordFragment.ARG_LINK, w.getImage());
adapter.addTab(R.string.title_section1, ImageWordFragment.class, args1);
Bundle args2 = new Bundle();
args2.putString(ImageWordFragment.ARG_LINK, w.getImage());
adapter.addTab(R.string.title_section1, ImageWordFragment.class, args2);
Bundle args3 = new Bundle();
args3.putString(ImageWordFragment.ARG_LINK, w.getImage());
adapter.addTab(R.string.title_section1, ImageWordFragment.class, args3);
//Notify Changes
adapter.notifyTabsChanged();
return convertView;
}
private class WordPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final Context mContext;
private final FragmentManager mFragmentManager;
private final ViewPager mViewPager;
final class TabInfo {
private final Class<?> mClass;
private final Bundle mArgs;
private final int mTitleRes;
TabInfo(Class<?> fragmentClass, Bundle args, int titleRes) {
mClass = fragmentClass;
mArgs = args;
mTitleRes = titleRes;
}
}
public WordPagerAdapter(FragmentManager fm, Context context, ViewPager pager) {
super(fm);
mFragmentManager = fm;
mContext = context;
//Setup view pager
mViewPager = pager;
mViewPager.setAdapter(this);
}
public void addTab(int titleRes, Class<?> fragmentClass, Bundle args) {
mTabs.add(new TabInfo(fragmentClass, args, titleRes));
}
public void notifyTabsChanged() {
notifyDataSetChanged();
}
public void setCurrentItem(int position) {
mViewPager.setCurrentItem(position);
}
public void setOffscreenPageLimit(int pages) {
mViewPager.setOffscreenPageLimit(pages);
}
#Override
public Fragment getItem(int position) {
TabInfo tab = mTabs.get(position);
return Fragment.instantiate(mContext, tab.mClass.getName(), tab.mArgs);
}
#Override
public int getCount() {
return mTabs.size();
}
}
}
Thsi is the fragment:
public class ImageWordFragment extends Fragment {
public static final String ARG_LINK = "ARG_LINK";
#InjectView(R.id.imageView)
ImageView imageView;
String imageUrl;
public ImageWordFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageUrl = getArguments().getString(ARG_LINK);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_word_image, container, false);
ButterKnife.inject(this, rootView);
new ImageLoadTask(imageUrl, imageView);
return rootView;
}
}

A couple of experiments indicate this is probably caused by your ViewPagers all having the same id (from the XML). Have you tried generating ids at runtime using View.generateViewId()?

Related

ViewPager with the dots only beginning on the third slide (3/3)

I've a ViewPager, with dots, and it's only beginning on the third slide [3/3].
But sometimes, the second slide is not showed in the ViewPager. I tried to use the Log, to show the initial position and the current position, when the position changes, and the result was: the second option is not showed, only the first and the third.
The resume of the hierarchy of my class is:
HelpHomeFragment extends BaseFragment {
ViewPagerAdapter extends PagerAdapter {}
HelpFrag1 extends Fragment {}
HelpFrag2 extends Fragment {}
HelpFrag3 extends Fragment {}
}
and my code is below:
HelpHomeFragment.java
public class HelpHomeFragment extends BaseFragment {
#BindView(R.id.llt_help_tipsbase)
LinearLayout llTips;
#BindView(R.id.vpg_help)
ViewPager viewPager;
#BindView(R.id.slider_dots)
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
private static final String ARG_PARAM1 = "Title";
private DataManager dm;
private HelpHomeFragmentPresenter<HelpHomeFragment> presenter;
private ListHelpsAdapter listHelpsAdapter;
private MyTimerTask mtt;
public static Fragment newInstance(String title) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, title);
Fragment fragment = new HelpHomeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dm = ((MvpApp) getActivity().getApplication()).getDataManager();
presenter = new HelpHomeFragmentPresenter<>(dm);
presenter.onAttach(this);
}
#Override
public void onResume() {
super.onResume();
showSlideshowTips();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_home, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void showSlideshowTips() {
configSlideshow();
}
#Override
public void configSlideshow() {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++)
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
dots[position].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
mtt = new MyTimerTask();
new Timer().scheduleAtFixedRate(mtt, 4500, 9000);
} catch (Exception e) {
e.printStackTrace();
}
}
// CUSTOM TIMER
class MyTimerTask extends TimerTask {
#Override
public void run() {
try {
getBaseActivity().runOnUiThread(() -> {
if (viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem(1);
} else if (viewPager.getCurrentItem() == 1) {
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
// CUSTOM PAGE ADAPTER
class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Fragment[] fragments = {new HelpFrag1(), new HelpFrag2(), new HelpFrag3()};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null;
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.custom_layout, null);
try {
View finalView = view;
getActivity().runOnUiThread(() -> getActivity().getSupportFragmentManager().beginTransaction()
.replace(finalView.getId(), fragments[position], "findThisFragment")
.addToBackStack(null).commit());
} catch (Exception e){
e.printStackTrace();
}
}
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
// classes fragment for the slideshow. Each fragment is an slide
public static class HelpFrag1 extends Fragment {
public HelpFrag1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_help_frag1, container, false);
}
}
// and more two classes HelpFrag, only changing the end (HelpFrag2 and HelpFrag3)
// and changing the layout to fragment_help_frag2 and fragment_help_frag3
}
and my layout base of the ViewPager is:
fragment_help_home.xml
<!-- another tag -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vpg_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:paddingTop="4dp"
android:layout_marginRight="30dp"
android:overScrollMode="never" />
<LinearLayout
android:id="#+id/slider_dots"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="-20dp"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal" />
</LinearLayout>
<!-- another tag -->

ViewPager [FragmentPagerAdapter] inside ListView

i'm trying to put ViewPager into ListView
here the code of ListView AdapterClass:
public class AdapterPager extends BaseAdapter {
.....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.component_pager, parent, false);
new ViewHolder(view, itemData.get(position));
}
return view;
}
View Holder:
private class ViewHolder {
ViewPager pager;
PagerAdapter pagerAdapter;
public ViewHolder(View view, ModelItem model){
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setId(model.getId()); /// uniq ID
pagerAdapter = new MyFragmentPagerAdapter(((FragmentActivity)view.getContext()).getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
then, Pager Adapter:
static final int PAGE_COUNT = 2;
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentComponentPager.newInstance(position, mModel);
}
#Override
public float getPageWidth(int position) {
float f_width = 1f;
return f_width;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
and, the last, Pager Fragment:
public class FragmentComponentPager extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
static final String ARGUMENT_NAME = "arg_name";
int pageNumber;
public static FragmentComponentPager newInstance(int page, ModelItem data) {
FragmentComponentPager pageFragment = new FragmentComponentPager();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
if (data != null){
arguments.putString(ARGUMENT_NAME, data.getName());
}
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.component_list, null);
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvTitle.setText(getArguments().getString(ARGUMENT_NAME));
return view;
}
}
when i run it ListView shows all items that i've added, but all of them, except the last one, with empty ViewPager.
and, if i removed pager.setId(model.getId()); the first item shows view pager, and the others empty.
guess that smth wrong with FragmentManager, but have no idea how deal with it :(
In your ViewHolder you need to call getChildFragmentManager instead of getSupportFragmentManager.

Access Fragment's TextView (inside a viewpager) from Activity

As the title says, I am trying to access (setText,etc) a TextView thats inside a fragment. The fragment is loaded into a viewpager in an activity. I want to access this TextView from the activity class.
private PagerAdapter mPagerAdapter;
private ViewPager pager;
FragmentPageOne fragPageOne;
FragmentPageTwo fragPageTwo;
Exert of Activity's onCreate:
fragPageOne= new FragmentPageOne();
fragPageTwo = new FragmentPageTwo();
mPagerAdapter = new ViewPagerAdapter(this, getSupportFragmentManager(),
fragPageOne.getClass(), fragPageTwo.getClass(),
);
pager = (ViewPager) findViewById(R.id.eventPager);
pager.setAdapter(mPagerAdapter);
ViewPagerAdapter class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Class<? extends Fragment>> fragmentsClasses;
private final Context context;
public EventViewPagerAdapter(Context context, FragmentManager fm, Class<? extends Fragment>... fragmentsClasses) {
super(fm);
this.context = context;
this.fragmentsClasses = Arrays.asList(fragmentsClasses);
}
public Fragment getItem(int position) {
return Fragment.instantiate(context, fragmentsClasses.get(position).getName());
}
#Override
public int getCount() {
return fragmentsClasses.size();
}
}
FragmentPageOne class (FragmentPageTwo's structure is similar.):
public class FragmentPageOne extends Fragment {
public View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
rootView = inflater.inflate(R.layout.fragment_page_1, container, false);
return (LinearLayout) rootView;
}
}
I am getting a null pointer (obviously) when i try to use this (within the activity itself):
TextView text = (TexView) pager.findViewById(R.id.textview1);
text.setText("hello world);
get your current fragment :
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
then get the view of the fragment to use findViewById from this view.
You're best bet is to do this in the instantiateItem override method in the pager adapter like so;
private LayoutInflater layoutInflater;
private Activity activity;
private int[] layouts;
public WalletViewPagerAdapter(int[] layouts , Activity activity) {
this.activity = activity;
this.layouts =layouts;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
if (position ==0) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}
container.addView(view);
return view;
}
The view you're trying to access is not yet available as at the time you're calling it. Try overriding the onViewCreated method then use the view parameter to get textView like so;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
TextView availableBalance = view.findViewById(R.id.available);
availableBalance.setText("N100,0000,000");
}

How do i make my fragment using a viewPager

i have a fragment which uses AsyncTask to download the JSON and display several NEWS segments. Here i can slide up and down and view all the News segments. But i want to slide this horizontally and view the news segments one by one by sliding. As far as i know (i'm a beginner) i have to use a ViewPager adapter to achive this.But i don't know how.Please someone help me.
My fragment class
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}
My ViewPager adapter
public class ViewPageAdapter extends PagerAdapter {
private LinkedHashMap<String, BaseElement> item;
private int page;
private Activity activity;
private LayoutInflater inflater;
private ViewPageAdapter(LinkedHashMap<String, BaseElement> item, int page,
Activity activity) {
super();
this.item = item;
this.page = page;
this.activity = activity;
}
#Override
public int getCount() {
return item.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(View container, int position) {
View view = null;
return view;
}
}
PageAdapter
public class PageAdapter extends FragmentStatePagerAdapter {
public static final String ARG_SECTION_NUMBER = "section_number";
private ArrayList<BaseElement> item;
private Activity activity;
public PageAdapter(FragmentManager fragmentManager,
ArrayList<BaseElement> item, Activity activity) {
super(fragmentManager);
this.activity = activity;
this.item = item;
}
#Override
public Fragment getItem(int position) {
// ------set fragment class for viewPager----------//
Fragment fragment = new PageSectionFragment();
Bundle bundle = new Bundle();
// ---- setPage position as agument for PageSectionFragment
// class---//
bundle.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return item.size();
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
FilmCategory film = (FilmCategory) item.get(position);
Sihala sinhla = new Sihala(activity);
return sinhla.getSinhalaString(film.getCategory());
}
}
Add this into your layout..
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never" />
Then Add this class into your Fragment class.
private class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
/*#Override
public android.support.v4.app.Fragment getItem(int position) {
return AlertSlideFragment.create(position);
}*/
#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.
tabFragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
tabFragment.setArguments(args);
/*fragment = getRegisteredFragment(0);*/
return tabFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container,
position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
Finally here is the DummySectionFragment
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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View rootView = null;
/*View rootView = inflater.inflate(R.layout.fragment_tabbed_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));*/
int screenNum = getArguments().getInt(ARG_SECTION_NUMBER);
//listAdapterAlert= new ListAdapterAlert(getActivity(), R.layout.alert_list);
if(screenNum == 0) // 0 for recent
{
rootView = inflater.inflate(R.layout.alert_list,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.tv);
}
else if(screenNum == 1) // 1 for by due date
{
rootView = inflater.inflate(R.layout.alert_list,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.tv);
}
else if(screenNum == 2) // 2 for by campaign
{
rootView = inflater.inflate(R.layout.campaign_alert,
container, false);
}
return rootView;
}
}
Hope it will help you.

ABS + ViewPager + manage orientation change

I am currently trying to implement an application with several Tabs and i must use also ViewPager.
The difficulty i'm facing is to manage screen orientation changes... Let me explain more in detail..
In portrait there is a player full screen (1fragment), in lanscape i want it to change to a list at the left and a player at the right (2fragment)
For now viewPager is blocking me, i've search through the internet and found nothing for this issu with abs + viewpager.
I think the problem can be related to the adapter. For now it takes a "Class" variable and instanciate the fragment from it.
Do you have an idea ?
Any suggestion is welcome ! Thanks !
Here is the code of my FragmentPagerAdapter :
public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context _context;
private final ActionBar _actionBar;
private final ViewPager _viewpager;
private final ArrayList<TabInfo> _tabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
_context = activity;
_actionBar = activity.getSupportActionBar();
_viewpager = pager;
_viewpager.setAdapter(this);
_viewpager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
_tabs.add(info);
_actionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount() {
return _tabs.size();
}
#Override
public Fragment getItem(int position) {
TabInfo info = _tabs.get(position);
return Fragment.instantiate(_context, info.clss.getName(), info.args);
}
#Override
public void onPageSelected(int position) {
_actionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < _tabs.size(); i++) {
if (_tabs.get(i) == tag) {
_viewpager.setCurrentItem(i);
}
}
}
}
Here is the SherlockFragmentActivity :
public class MainActivity extends SherlockFragmentActivity {
private ViewPager _viewPager;
private PagerTitleStrip _pagerStrip;
private ActionBar _actionBar;
private TabsAdapter _tabsAdapter;
private Tab _radioTab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_viewPager = (ViewPager) findViewById(R.id.viewpager);
_actionBar = getSupportActionBar();
_tabsAdapter = new TabsAdapter(this, _viewPager);
_radioTab = _actionBar.newTab().setCustomView(getTabIndicator(getString(R.string.radio_tab), android.R.drawable.ic_menu_manage));
_tabsAdapter.addTab(_radioTab, FragmentRadio.class, null);
}
private View getTabIndicator(String text, int drawable) {
View indicator = _inflater.inflate(R.layout.tabs, null);
((TextView) indicator.findViewById(R.id.tab_title)).setText(text);
((ImageView) indicator.findViewById(R.id.tab_icon)).setImageResource(drawable);
return indicator;
}
}
The class FragmentRadio :
public class FragmentRadio extends SherlockFragment {
private View _view;
public FragmentRadio() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
_view = inflater.inflate(R.layout.fragment_radio, container, false);
return _view;
}
}
The layout fragment_radio :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_radio_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/fragment_radio"
android:name="com.egdigital.testing.ContentRadioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The class ContentRadioFragment :
public class ContentRadioFragment extends SherlockFragment {
// log
private static final String TAG = ContentRadioFragment.class.getSimpleName();
// ihm
private View _view;
private Button _btnPlay;
private Button _btnPause;
private ImageView _imageViewCover;
private ScrollingTextView _textViewName;
private TextView _textViewState;
private SeekBar _seekBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
_view = inflater.inflate(R.layout.content_radio, container, false);
_btnPlay = (Button) _view.findViewById(R.id.btn_play);
_btnPause = (Button) _view.findViewById(R.id.btn_pause);
_textViewName = (ScrollingTextView) _view.findViewById(R.id.tv_title);
_textViewState = (TextView) _view.findViewById(R.id.tv_buffering);
_seekBar = (SeekBar) _view.findViewById(R.id.seekBar1);
return _view;
}
}
And the layout content_radio is a normal layout

Categories

Resources