I've used ViewPagerIndicator to get WalkThrough like most popular application. But I can't understand how to add Pictures in ViewPager which shows how to use the application.
What I want is like these Walk Through.
What i got till now.
I dunno
How to add Custom View like ImageView and TextView in ViewPager?
Any guidance would be most welcome.
Since the question really old, I'll just write a short general guideline:
To populate viewpager with content, you add fragments to an adapter and then you set the adapter to the viewpager. You can do pretty much any layout in the fragment, putting there images/text etc..
As Inteist suggest, one can put any layout in fragment and supply that fragment to adapter.
Fragment:
public final class SelectModelFragment extends Fragment {
private static final String KEY_CONTENT = "SelectModelFragment:Content";
private static String TAG = SelectModelFragment.class.getSimpleName();
private SelectModel mSelectModelObj;
private CircularImageView mImageView;
public static SelectModelFragment newInstance(SelectModel obj) {
SelectModelFragment fragment = new SelectModelFragment();
fragment.mSelectModelObj =obj;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mSelectModelObj = savedInstanceState.getParcelable(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_select_model, container, false);
mImageView = (CircularImageView)view.findViewById(R.id.fragment_select_model_iv);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_CONTENT, mSelectModelObj);
}
}
Fragment Adapter :
public class SelectModelAdapter extends FragmentPagerAdapter {
ArrayList<SelectModel> mList;
private int mCount;
private static final String TAG = SelectModelAdapter.class.getSimpleName();
public SelectModelAdapter(FragmentManager fm, ArrayList<SelectModel> mList) {
super(fm);
this.mList = mList;
mCount = mList.size();
}
#Override
public Fragment getItem(int position) {
return SelectModelFragment.newInstance(mList.get(position));
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TAG;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Activity: Where ViewPager has Fragment Adapter which feeds Fragment.
public class SelectModelActivity extends BaseSliderActivity {
private ViewPager mPager;
private SelectModelAdapter mAdapter;
private ArrayList<SelectModel> mList;
private void setAdapter() {
mAdapter = new SelectModelAdapter(getSupportFragmentManager(), mList);
mPager.setAdapter(mAdapter);
mIndicator.setViewPager(mPager);
}
}
Related
I faced an issue with ViewPager and ViewPagerAdapter in Android.
I use a viewpager with 2 static fragments (one using a textEdit and the second one using a listview). Theyr are working pretty good.
But i have a problem with the third fragment which is dynamic.
It uses the camera and has to be instanciated, destroyed, re-instanciated following a scenario. So, the ViewPagerAdapter could contain 2 or 3 framents.
The problem appears when I re-instaciate the third fragment, I got a NPE after OnCreateView() (the main layout view is null after this method, but is not null inside the method).
There is the code for the main activity :
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager();
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
The setupViewPager() :
private void setupViewPager() {
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mTabFragmentDocument = new TabFragmentDocument();
mTabFragmentDocument.setApp(this);
mTabFragmentText = new TabFragmentText();
mTabFragmentText.setApp(this);
mViewPagerAdapter.addFragment(mTabFragmentText, AbstractDefiner.TEXT);
mViewPagerAdapter.addFragment(mTabFragmentDocument, AbstractDefiner.DOCUMENT);
mViewPager.setAdapter(mViewPagerAdapter);
}
To create the third fragment :
mTabFragment = new TabFragment();
mTabFragment .setApp(this);
mViewPagerAdapter.addFragment(mTabFragment, "THIRD");
mViewPagerAdapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(2);
mViewPagerAdapter.notifyDataSetChanged();
mTabFragment .setParams(tmp[1], tmp[2], tmp[3], tmp[4]);
mTabFragment .setupView();
mTabFragment .startWork();
}
}, 1000);
And to destroy it :
mViewPager.setCurrentItem(0);
mViewPager.removeViewAt(2);
mTabFragment .onDestroy();
mViewPagerAdapter.remove(2);
mViewPagerAdapter.notifyDataSetChanged();
mTabFragment = null;
Then, the Adapter code :
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void remove(int index) {
mFragmentList.remove(index);
mFragmentTitleList.remove(index);
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Finally, the code of the third fragment :
public class TabFragment extends Fragment implements SurfaceHolder.Callback,
GLSurfaceView.Renderer {
private static final String LOGCAT = "WEB_RTC_VISIO";
private HomeActivity mApp;
private String p1;
private String p2;
private String p3;
private String p4;
private VideoSource mLocalVideoSource;
private VideoRenderer.Callbacks mLocalRenderer;
private VideoRenderer.Callbacks mRemoteRenderer;
private GLSurfaceView mVideoView;
private SurfaceView mDrawView;
private SurfaceHolder mDrawHolder;
private ImageView mCursor;
private String mBgBytesString;
private ImageView mImgView;
private View mV;
public TabFragment() {
// Required empty public constructor
}
public void setApp(HomeActivity app) {
mApp = app;
}
public void setParams(String p1, String p2, String p3,
String p4) {
this.p1= p1;
this.p2= p2;
this.p4= p4;
this.p3= p3;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mV = inflater.inflate(R.layout.third_layout, container, false);
return mV;
}
#Override
public void onDetach() {
super.onDetach();
}
public void setupView() {
RequestUserPermission requestUserPermission = new RequestUserPermission(mApp);
requestUserPermission.verifyStoragePermissions();
mImgView = (ImageView) mV.findViewById(R.id.img_display); // NPE HERE
TextView mTest1= (TextView) mV.findViewById(R.id.test1);
mRequestLabelTextView.setText("test 1");
TextView mTest2= (TextView) mV.findViewById(R.id.test2);
mEquipmentSerialTextView.setText("test 2");
// View that displays the view from the camera
mVideoView = (GLSurfaceView) mV.findViewById(R.id.gl_surface);
// View that displays the cursor and drawing associated
mDrawView = (SurfaceView) mV.findViewById(R.id.draw_surface);
mDrawHolder = mDrawView.getHolder();
mDrawHolder.setFormat(PixelFormat.TRANSPARENT);
mDrawHolder.addCallback(this);
// Image of the cursor
mCursor = (ImageView) mV.findViewById(R.id.mouseCursor);
// Some more inits
}
public void startWork() {
//SOME WORK
}
}
So, the first instanciation is ok, but at the second, I got the NPE on getting the ImageView...
Someone can help me understanding this problem please ?
Thanks in advance !
Try using FragmentStatePagerAdapter not FragmentPagerAdapter it will solve many problems. Hope it will gonna work for you too.
I have 4 Fragments in a ViewPager that is integrated with a TabLayout. Each of those Fragments holds a RecyclerView because I'm displaying an unknown amount of list items. The items are loaded by date, so I have two buttons that let you change days, and then the appropriate data in the list items is loaded based on the date that is set. The buttons are part of the outer activity.
Everything so far works perfectly BUT once I rotate the device the fragments don't load anything. Nothing is displayed inside the Fragments. The views in the outer activity are displayed fine though. The weird thing is that if I touch one of the buttons that changes the date, the Fragments are loaded and the data is displayed correctly. But I need everything to be displayed immediately after rotation not just when I click one of those buttons. Here is my code:
public class MainActivity extends AppCompatActivity implements DatePickerFragment.DateDialogInterface
{
private final static String COLOR_CONTROL_CHOSEN = "color_control_chosen";
private static final String DIALOG_DATE = "dialog_date";
private static final String TAG = "MainActivity";
private static final String SET_LOCATION = "set_location";
public static final String LEAGUE_POSITION = "league_position";
private Toolbar mToolbar;
private ViewPager mViewPager;
private TabLayout mTabLayout;
private ImageButton mPrevDateButton, mNextDateButton;
private TextView mDateTextView, mLeagueTextView;
private String mTodaysDate;
private Date mLastSelectedDate, mTodaysDateObj;
private ProgressBar mProgressBar;
private FragmentPagerAdapter mAdapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.outnix_toolbar);
mViewPager = (ViewPager) findViewById(R.id.main_activity_view_pager);
mTabLayout = (TabLayout) findViewById(R.id.main_activity_tab_layout);
mDateTextView = (TextView) findViewById(R.id.display_date_text_view);
mLeagueTextView = (TextView) findViewById(R.id.league_title_header);
mPrevDateButton = (ImageButton) findViewById(R.id.previous_date_button);
mNextDateButton = (ImageButton) findViewById(R.id.next_date_button);
mProgressBar = (ProgressBar) findViewById(R.id.loading_circle);
mProgressBar.setVisibility(View.GONE);
setTodaysDate();
mDateTextView.setText("Today");
setSupportActionBar(mToolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayShowTitleEnabled(false);
NavDrawerFragment navDrawerFrag = (NavDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_nav_drawer);
navDrawerFrag.setUp((DrawerLayout) findViewById(R.id.nav_drawer), mToolbar);
setUpViewPagerAdapterOnCreate();
mTabLayout.setupWithViewPager(mViewPager);
mDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager fm = getSupportFragmentManager();
DatePickerFragment dialog = new DatePickerFragment();
Bundle args = new Bundle();
args.putSerializable("ARG_DATE", mLastSelectedDate);
dialog.setArguments(args);
dialog.show(fm, DIALOG_DATE);
}
});
THESE TWO LISTENERS ARE WHAT DISPLAY THE DATA AFTER A ROTATION CHANGE
//////////////////////////////////////////////////////////////////
mPrevDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
mProgressBar.setVisibility(View.VISIBLE);
updateDate(-1);
setupViewPagerAdapter(getViewPagerPos());
}
});
mNextDateButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mProgressBar.setVisibility(View.VISIBLE);
updateDate(1);
setupViewPagerAdapter(getViewPagerPos());
}
});
}
////////////////////////////////////////////////////////////////////
/* #Override
protected void onResume()
{
super.onResume();
setupViewPagerAdapter(getViewPagerPos());
}*/
private void setUpViewPagerAdapterOnCreate() //only called when opened from LauncherActivity
{
setupViewPagerAdapter(0);
int touchColorPixel = getIntent().getIntExtra(COLOR_CONTROL_CHOSEN, ContextCompat.getColor(this, R.color.blue));
if(touchColorPixel == ContextCompat.getColor(this, R.color.orange))
mViewPager.setCurrentItem(0);
else if(touchColorPixel == ContextCompat.getColor(this, R.color.blue))
mViewPager.setCurrentItem(1);
else
mViewPager.setCurrentItem(3);
}
private void setupViewPagerAdapter(int currentPos)
{
mAdapterViewPager = new MainPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapterViewPager);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setCurrentItem(currentPos);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putSerializable(DIALOG_DATE, mLastSelectedDate); //save the last date selected (or last date displayed) on rotation change.
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
setDateFromDialog((Date) savedInstanceState.getSerializable(DIALOG_DATE)); //restore the last date selected to the new rotation change
}
public ProgressBar getProgressBar()
{
return mProgressBar;
}
#Override
public void setDateFromDialog(Date date)
{
String newDate = getFormattedDate(date);
updateTodaysDate();
mLastSelectedDate = date;
setupViewPagerAdapter(getViewPagerPos());
if(newDate.equals(mTodaysDate))
mDateTextView.setText("Today");
else
mDateTextView.setText(newDate);
}
private int getViewPagerPos()
{
return mViewPager.getCurrentItem();
}
}
The 2 buttons mPrevDateButton and mNextDateButtonare the buttons that when clicked "fix" the problem. Inside their click listeners, the updateDate() method is only doing stuff related to a TextView object and is why I didn't include the definitions (I'm trying to keep the post as short as possible). So I know for sure it has something to do with my setupViewPagerAdapter() method. I've tried adding this method in onCreate() and onResume() but the Fragments still stay blank.
Here is my ViewPager adapter code:
public class MainPagerAdapter extends FragmentPagerAdapter
{
private final String[] mFragmentTitleList = {"My Games", "All Games", "All Places", "My Places"}; //tab title names
private final static int NUM_FRAGMENTS = 4;
public MainPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch(position)
{
case 0:
return MyGamesFragment.newInstance();
case 1:
return AllGamesFragment.newInstance();
case 2:
return AllPlacesFragment.newInstance();
case 3:
return MyPlacesFragment.newInstance();
default:
return null;
}
}
#Override
public int getCount()
{
return NUM_FRAGMENTS;
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitleList[position];
}
}
Here is one of the 4 fragments. They pretty much all have similar design.
public class AllGamesFragment extends Fragment
{
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mAllGamesRecyclerView;
private GameAdapter mGameAdapter;
private List<Game> mGameList = new ArrayList<>();
private MainActivity mMainActivity; //keeps a reference to MainActivity to access public methods
public static AllGamesFragment newInstance()
{
return new AllGamesFragment();
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
mMainActivity = (MainActivity) context;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
mMainActivity.getProgressBar().setVisibility(View.VISIBLE);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.recycler_view_all_games, container, false);
mAllGamesRecyclerView = (RecyclerView) view.findViewById(R.id.all_games_recycler_view);
mAllGamesRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
#Override
public void onRefresh()
{
getGamesData();
mSwipeRefreshLayout.setRefreshing(false);
}
});
return view;
}
#Override
public void onResume()
{
super.onResume();
getGamesData();
}
private void setupAdapter()
{
if(isAdded())
{
mGameAdapter = new GameAdapter(mGameList);
mAllGamesRecyclerView.setAdapter(mGameAdapter);
}
}
private void getGamesData()
{
new GetDataTask(mMainActivity.getLastSelectedDate()).execute();
}
private class GetDataTask extends Scraper.GameDataTask
{
GetDataTask(Date date)
{
super(date, getActivity());
}
#Override
protected void onPostExecute(List<Game> games)
{
mGameList = games;
setupAdapter();
mMainActivity.getProgressBar().setVisibility(View.GONE);
}
}
private class GameAdapter extends RecyclerView.Adapter<GameHolder>
{
private List<Game> mGames;
public GameAdapter(List<Game> games)
{
mGames = games;
}
#Override
public GameHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout.list_game_item, parent, false);
return new GameHolder(view, getActivity());
}
#Override
public void onBindViewHolder(GameHolder holder, int position)
{
holder.bindGameData(mGames.get(position));
}
#Override
public int getItemCount()
{
return mGames.size();
}
}
I've looked at so many posts on here, changed my code many times and I still can't get it to work. I'm just baffled that it "fixes" when I click one of the date buttons. If you would like me to post more code of something let me know. Sorry for the long post but I feel the context is needed. I really appreciate any help!
I figured it out! I had to switch to a FragmentStatePagerAdapter rather than use a FragmentPagerAdapter. I believe it has something to do with the Fragments being destroyed and recreated again.
I also read that another way would be to wrap the ViewPager in a Fragment and when you create its adapter you use getChildFragmentManager() rather than getSupportFragmentManager() like this:
mAdapterViewPager = new MyPagerAdapter(getChildFragmentManager());
I didn't want to have to add an entire Fragment around my ViewPager just to fix this issue so I switched to using FragmentStatePagerAdapter and it worked! Hope this helps someone else out there.
Making viewPager adapter extends FragmentStatePagerAdapter and not FragmentPagerAdapter should solve the problem.
I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.
Hii My question is i have 6 frgments and i am using ViewPager to navigate from one page to another vise-versa.but i want after 6th fragment by one horizontal forward swipe to comeback to 1 Fragment .like from 6->1
Try to add the first fragment one more time at the end of the queue and when it is loaded, use viewPager.setCurrentItem(0, false) to move to the first fragment.
Actualy, it does not always work. Referring to this answer ViewPager as a circular queue / wrapping,
I made a simple example have a look :
public class MainActivity extends FragmentActivity {
private static final int NUM_PAGES = 6;
private ViewPager pager;
private PagerAdapter pagerAdapter;
private List<SlideFragment> slideList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slideList = new ArrayList<SlideFragment>();
for (int i = 0; i<NUM_PAGES; i++){
SlideFragment slide = new SlideFragment();
slide.setIndex(i+1);
slideList.add(slide);
}
pager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % NUM_PAGES;
return slideList.get(_pos);
}
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
}
}
And the Fragment class :
public class SlideFragment extends Fragment {
private int index;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup)inflater.inflate(R.layout.slide, container, false);
TextView tw = (TextView) root.findViewById(R.id.textView);
tw.setText(Integer.toString(index));
return root;
}
public void setIndex(int index){
this.index = index;
}
}
i dont understand the use for fragments in android, and im use the viewpagelibrary (https://github.com/JakeWharton/Android-ViewPagerIndicator)
I try to use fragments with this. I have fragmentacitivy this this code:
public class FragmentosActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.fragmentos_layout);
// initialsie the pager
this.inicializaPaginas();
}
//Este metodo inicia todos los fragments
private void inicializaPaginas() {
FragmentAdapter adapter =
new FragmentAdapter(getSupportFragmentManager());
adapter.addFragment(new Mapa());
adapter.addFragment(new Cercanos());
ViewPager pager = (ViewPager) super.findViewById(R.id.indicator);
pager.setAdapter(this.mPagerAdapter);
}
FragmentAdapter
public class FragmentAdapter extends FragmentPagerAdapter {
List<Fragment> fragments = null;
public FragmentAdapter(FragmentManager fm) {
super(fm);
fragments = new ArrayList<Fragment>();
}
public void addFragment(Fragment fragment){
fragments.add(fragment);
}
#Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
#Override
public int getCount() {
return fragments.size();
}
}
and viewpager adapter (is an adapter for the library)
public class ViewPagerAdapter extends PagerAdapter implements TitleProvider
{
private static String[] titles = new String[]
{
"Listado",
"Mapa"
};
private final Context context;
public ViewPagerAdapter( Context context )
{
this.context = context;
}
#Override
public String getTitle( int position )
{
return titles[ position ];
}
#Override
public int getCount()
{
return titles.length;
}
#Override
public Object instantiateItem( View pager, int position )
{
LinearLayout v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.cercanos, null);
if (position == 0) {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.cercanos, null);
} else {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.mapa, null);
}
((ViewPager) pager).addView(v, 0);
return v;
}
#Override
public void destroyItem( View pager, int position, Object view )
{
}
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
#Override
public void finishUpdate( View view ) {}
#Override
public void restoreState( Parcelable p, ClassLoader c ) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate( View view ) {}
}
and fragment_layout is:
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.viewpagerindicator.TitlePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/Widget.IndicadorTitulo" />
/>
</LinearLayout>
and mapa.class and cercanos.class are class that extends of fragment without code.
The app dont show noting, it crashes and show me "can't instantiate class com.rbrlnx.controles.FragmentAdapter; no empty constructor "
Im looking for fragments example tutorial but all are very dificults to learn and traduce (Im spanish) anyone can help me please? If u have easy code to learn for fragments will its perfect.
Thanks
have you already solved your problem?
your message:
can't instantiate class com.rbrlnx.controles.FragmentAdapter; no empty constructor
looks like you maybe haven't have a:
public static HistoryFragment newInstance(Context context, TextView textViewSubText)...
public void onActivityCreated(Bundle savedInstanceState)...
or..
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
method.
can you post your stacktrace message?
cheers,
mike