I recently have started programming again for the android and am currently working on a app that I would like to implement horizontal view pagers so the user in one instance can swipe between two pages to enter/update information and in a later instance swipe between four pages to view information that they have entered/updated. I am basically making an electronic character sheet for roleplaying games.
I have been working off of these tutorials for horizontal view pagers:
http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/
http://manishkpr.webheavens.com/android-viewpager-example/
My question is of all the tutorials I have seen, the h. view pager is used off of the main activity screen, is there a way to implement the horizontal view pager off of a subsequent screen? Every time I have tried to implement the code to work off of a page other than a main screen it has crashed as soon as I got to that page.
So, long story short, has anyone successfully implemented horizontal view pagers on a non main page and if so, how?
I hope that I have made sense, but if you have any further questions please let me know!
08-24 01:44:34.310: I/ActivityManager(144): START {cmp=com.echaractersheet/.CharacterStats1} from pid 15115
08-24 01:44:34.360: D/AndroidRuntime(15115): Shutting down VM
08-24 01:44:34.360: W/dalvikvm(15115): threadid=1: thread exiting with uncaught exception (group=0x40a581f8)
08-24 01:44:34.370: E/AndroidRuntime(15115): FATAL EXCEPTION: main
08-24 01:44:34.370: E/AndroidRuntime(15115): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.echaractersheet/com.echaractersheet.CharacterStats1}: java.lang.NullPointerException
characterstats.xml:
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/characterstatspager" />
characterstats1.xml and characterstats2.xml are the two pages I want to swipe between
CharacterStatsPagerAdapter.java:
...
public class CharacterStatsPagerAdapter extends PagerAdapter {
public int getCount() {
return 2;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId =0;
switch (position) {
case 0:
resId = R.layout.characterstats1;
break;
case 1:
resId = R.layout.characterstats2;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
CharacterStats1.java:
CharacterStatsPagerAdapter adapter = new CharacterStatsPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.characterstatspager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
well the pager will work with the data in the adapter, so as long as you keep the objects in the adapter, you are good to go. so maybe before going to the next screen you should save the objects in the adapter (maybe to a static field in another class, just for a moment) and when you get to the new page you can retrieve the objects and put them in the adapter of the new viewpager and add the new pages. That is what i will do in your case.
UPDATE:
this is just an example, this needs more lines of code, but is a good start.
public class Fields {
private String name;
private String lastName;
private int age;
private boolean male;
public Fields(){
this.name = "";
this.lastName = "";
}
public Fields(String name, String lastName, int age, boolean male) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.male = male;
}
public View getRepresentation(Context mContext){
/*Create the view that ViewPager will display*/
LinearLayout layout = new LinearLayout(mContext);
layout.addView(new TextView(mContext)); //Name
layout.addView(new TextView(mContext)); //LastName
layout.addView(new TextView(mContext)); //Age
layout.addView(new CheckBox(mContext)); //Male/Female
return layout;
}
}
The View Pager Adapter
public class ViewPagerAdapter extends PagerAdapter {
private List<Fields> pages;
private Context mContext;
public ViewPagerAdapter( Context mContext )
{
this.mContext = mContext;
}
public void setPages(List<Fields> pages){
this.pages = pages;
}
public List<Fields> getPages(){
return this.pages;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public Object instantiateItem( View pager, int position )
{
View view = pages.get(position).getRepresentation(mContext);
view.setId(position);
return view;
}
#Override
public void destroyItem( View pager, int position, Object view )
{
((ViewPager)pager).removeViewInLayout( (View) view );
}
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
}
Main Class
public class MainActivity extends Activity {
private Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = getApplicationContext();
setContentView(R.layout.viewpager_layout);
final List<Fields> fields = new ArrayList<Fields>();
fields.add(new Fields());
ViewPager mPager = (ViewPager) this.findViewById(R.id.viewpager);
Button nextActivity = (Button) this.findViewById(R.id.nextAct);
ViewPagerAdapter mAdapter = new ViewPagerAdapter(mContext);
mAdapter.setPages(fields);
mPager.setAdapter(mAdapter);
nextActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SecondActivity.pages = fields;
Intent intent = new Intent(mContext, SecondActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Second Class
public class SecondActivity extends Activity {
public static List<Fields> pages;
private Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = getApplicationContext();
setContentView(R.layout.viewpager_layout);
final List<Fields> fields = pages;
pages = null;
fields.add(new Fields()); //Add the new Pages
ViewPager mPager = (ViewPager) this.findViewById(R.id.viewpager);
Button nextActivity = (Button) this.findViewById(R.id.nextAct);
ViewPagerAdapter mAdapter = new ViewPagerAdapter(mContext);
mAdapter.setPages(fields);
mPager.setAdapter(mAdapter);
nextActivity.setVisibility(View.GONE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
As i said, this is JUST AN EXAMPLE, the Fields Class should be changed for your Objects, the ViewPagerAdapter is where you keep the list of pages that you will pass to the next activity.
And the static field on the secondactivity is just to be use as a bridge between activities and
should not be overuse, thats is why after fetching the data you need to set to NULL to know that you
already grabbed the value. Hope it helps.
NOTE: THIS CODE WILL NOT WORK AS IT IS, need more code.
Related
I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them.
For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle.
I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.
Reloading calls
I've tried using GotCampDetails() which sets the local variable in the class.
viewPager.setCurrentItem(0);
in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.
What am I missing?
public class ViewPagerFragment extends Fragment implements WebReadResultsListener {
private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.camp_viewpager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (campDetails != null && ! campDetails.isEmpty()) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
#Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
this.campDetails = campDetails;
return true;
}
#Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Handle orientation changes here
}
}
Adapter:
public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;
public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
this.campDetails=campDetails;
this.mContext = context;
this.viewPager = viewPager;
colorChangeListener = (ColorChangeListener) mContext;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
currentposition = pos;
if (campDetails.get(currentposition).get("color").equals("green")) {
color = green;
} else {
color = pink;
}
ColorAppBar(color);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public Object instantiateItem(ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);
if (campDetails.size() <= 0) {
Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
return null;
}
if (campDetails.get(position).get("description").equals("RD") ) {
layout.setBackgroundColor(mContext.getResources().getColor(green));
} else {
layout.setBackgroundColor(mContext.getResources().getColor(pink));
}
collection.addView(layout);
this.collection = collection;
TextView eName = (TextView) layout.findViewById(R.id.en);
TextView nEName= (TextView) layout.findViewById(R.id.nen);
TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
// ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);
eName.setText(campDetails.get(position).get("name"));
if (position+1 < campDetails.size()) {
nEName.setText(campDetails.get(position+1).get("name"));
textView6.setVisibility(View.VISIBLE);
} else {
nEName.setText("You are DONE!!");
textView6.setVisibility(View.INVISIBLE);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return campDetails.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return campDetails.get(position).get("name");
}
#Override
public void ColorAppBar(int color) {
colorChangeListener.ColorAppBar(color);
}
}
I finally managed to get it done.
I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly.
Here is what I added in case someone else may find it useful:
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(pos);
}
}, 100);
I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager
hope it helps
I have a ListView which contains product details. On Item click of listview I open new activity with particular product detail. I wanted to convert activity to ViewPager so that I can swipe to load next and previous records in same fragment. Fragment structure will be same for all records. I don't know from where should I start. Can you give me overview idea how to achieve this. Here is my model class.
Product.java
public class Product implements Serializable{
public int id;
public String Name;
public String description;
public String longDescription;
public String amount;
public String image;
}
Here is my FragmentPagerAdapter class
ProductPagerAdapter.java
public class ProductPagerAdapter extends FragmentPagerAdapter {
private Context context;
private ArrayList<Product> list;
public ProductPagerAdapter(FragmentManager fm, Context context, ArrayList<Product> list) {
super(fm);
this.context = context;
this.list = list;
}
#Override
public Fragment getItem(int position) {
return ProductFragment.newInstance(position);
}
#Override
public int getCount() {
return list.size();
}
}
And this is my Fragment
ProductFragment.java
public class ProductFragment extends Fragment {
public ProductFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_product, container, false);
//findViewById...
return v;
}
public static Fragment newInstance(int id) {
Bundle args = new Bundle();
args.putInt("Id", id);
ProductFragment fragment = new ProductFragment();
fragment.setArguments(args);
return fragment;
}
}
And now on list item Click I am opening new activity. And I am sending Product object to it.
lv_itemRateList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
Product r = new Product();
r = rateListArrayList.get(i);
intent.putExtra("product",r);
startActivity(intent);
}
});
My DetailsActivity contains my viewpager. Now can someone tell me how to do this?
1-) Need a custom adapter for ViewPager.
I assumed that all the pages will have the same content, so all of them have the same layout so ProductPagerAdapter extends the PagerAdapter.
public class ProductPagerAdapter extends PagerAdapter
{
//variables
private Context context;
private ArrayList<Product> list;
private Product product
//views
TextView txtName ;
public ProductPagerAdapter(Context context, List<Product> list)
{
this.context = context;
this.list = list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ( object);
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
product = list.get(position);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.fragment_product, container,false);
txtName = (TextView) itemView.findViewById(R.id.txtName);
txtName.setText(product.Name)
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((LinearLayout) object);
}
}
2-) Adapter is ready. Now let's prepare the activity that will show the details. First initialize ViewPager and ProductPagerAdapter. Then show the details of the item which is selected by clicking on the previous activity.
public class DetailsActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
//getting product object
Intent intent = getIntent();
Product product = (Product) getIntent().getSerializableExtra("product");
//get selected item id
int selectedItemID = 0;
for(int i = 0 ; i < list.size() ; i++)
{
if(list.get(i).id == product.id)
{
selectedItemID = i;
break;
}
}
//Init ViewPager and adapter
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ProductPagerAdapter detailAdapter = new ProductPagerAdapter(DetailActivity.this, list);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(detailAdapter);
viewPager.setCurrentItem(selectedItemID); // set selection
viewPager.setPageTransformer(true, new ForegroundToBackgroundTransformer()); //custom transformer
...
}
}
3-) We've done what we have to do so far. So it will work like this. But what I would like to point out is that there are a few things to make the ViewPager better.
Performance : Use Parcelable instead of Serializable. Parcelable takes more time to implement but it will perform 10 times faster and use less resources. Please check this SO answer
Animation : You may want to need animations for transforming ViewPager. I suggest you to use ViewPagerTransforms
Indicators : If you want to use the paging indicator, I recommend ViewPagerIndicator.
For more on ViewPager
Below is an screenshot from my app.
This screen is a fragment that has sliding tabs layout. It will hold another fragment that will show data in listview. The problem is, in order to load data the value selected from the spinner need to pass within the fragment in tab. I am not getting idea how to do this. One approach would be the tab fragment would implement a callback and within that callback data should be loaded. But I am not getting how to register that callback in onItemSelected of spinner.
Note: All fragments within the tab will show data in listview only, so I have created a common fragment.
This is my code so far:
Fragment for the screenshot
public class BuyListingFragment2 extends BaseFragment {
private Context ctx;
private Spinner vehicle_type;
private ArrayList<ListingTabModel> mListingTabs = new ArrayList<ListingTabModel>();
private ArrayAdapter<String> spinnerAdapter;
private ArrayList<String> vehicleTypeSpinnerlist;
private int spinnerPosition;
private SlidingTabLayout sliding_tabs;
private BuyListingPagerAdapter buyListingPagerAdapter;
public static BuyListingFragment2 newInstance(String category,
int position, String preselectedFilters) {
BuyListingFragment2 fragment = new BuyListingFragment2();
Bundle args = new Bundle();
args.putString("vehicle_type", category);
args.putInt("spinner_position", position);
fragment.setArguments(args);
return fragment;
}
public BuyListingFragment2() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.vehicleType = getArguments().getString("vehicle_type");
this.selectedVehicle = this.vehicleType;
this.spinnerPosition = getArguments().getInt("spinner_position");
ArrayList<CategoryType> vehicleTypeList = RegistrationResponse
.getInstance().getVehicleTypeList();
spinnerAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vehicleTypeList);
buyListingPagerAdapter = new BuyListingPagerAdapter(
getChildFragmentManager(), mListingTabs);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ctx = getActivity();
vehicle_type = (Spinner) view.findViewById(R.id.vehicle_type);
vehicle_type.setAdapter(spinnerAdapter);
vehicle_type.setSelection(spinnerPosition, false);
if (mListingTabs.isEmpty()) {
String[] tabNames = getResources().getStringArray(
R.array.listing_tab_names);
for (int i = 0; i < tabNames.length; i++) {
String tabName = tabNames[i];
ListingTabModel mListingTabModel = new ListingTabModel();
mListingTabModel.setTagName(tabName);
mListingTabs.add(mListingTabModel);
}
}
buyListingPagerAdapter.notifyDataSetChanged();
listing_layout_viewpager = (ViewPager) view
.findViewById(R.id.listing_layout_viewpager);
listing_layout_viewpager.setAdapter(buyListingPagerAdapter);
sliding_tabs = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
sliding_tabs.setDistributeEvenly(true);
sliding_tabs.setViewPager(listing_layout_viewpager);
vehicle_type.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
spinnerPosition = position;
//How to register listener here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Common Fragment inside Tab
public class ListingFragment extends BaseFragment implements
OnSpinnerDataSelected {
private InfiniteListView mListView;
private BuyListingListAdapter buyListingAadapter;
private RobotoLightTextView emptyMessage;
private int currentPageNumber = 1;
private int totalPages;
private HashMap<String, String> params = new HashMap<String, String>();
private int apiCallCount = 0;
private Context ctx;
private String vehicleType;
private ProgressBar progressBar;
public ListingFragment() {
}
public static ListingFragment newInstance(ListingTabModel mListingTabModel) {
ListingFragment mFragment = new ListingFragment();
Bundle bundle = new Bundle();
// bundle.putBoolean("is_grid_view", mListingTabModel.isShowGridView());
// bundle.putString("vehicle_type", mListingTabModel.getVehicleType());
mFragment.setArguments(bundle);
return mFragment;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ctx = getActivity();
emptyMessage = (RobotoLightTextView) view
.findViewById(R.id.empty_message);
mListView = (InfiniteListView) view.findViewById(R.id.lstVw_buy);
boolean isGrid = getArguments().getBoolean("is_grid_view");
vehicleType = getArguments().getString("vehicle_type");
buyListingAadapter = new BuyListingListAdapter(ctx,
mVehicleListingList, isGrid);
mListView.setAdapter(buyListingAadapter);
progressBar = new ProgressBar(ctx);
}
#Override
public int getLayoutId() {
return R.layout.layout_messages;
}
#Override
public void onSpinnerDataSelected(String vehicleCategory) {
// TODO: fetch listing data
}
}
Callback implemented by the ListingFragment
public interface OnSpinnerDataSelected {
void onSpinnerDataSelected(String vehicleCategory);
}
FragmentStatePagerAdapter
public class BuyListingPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<ListingTabModel> mFragmentsList;
public BuyListingPagerAdapter(FragmentManager fm,
ArrayList<ListingTabModel> mFragmentsList) {
super(fm);
this.mFragmentsList = mFragmentsList;
}
#Override
public Fragment getItem(int index) {
ListingFragment listingFragment = ListingFragment
.newInstance(mFragmentsList.get(index));
return listingFragment;
}
#Override
public int getCount() {
return mFragmentsList.size();
}
#Override
public CharSequence getPageTitle(int position) {
String tagName = mFragmentsList.get(position).getTagName();
tagName = tagName.replace("_", " ");
return tagName;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return object == view;
}
}
When using one activity and multiple fragments, I suggest to let the Fragment manage the UI and use the Activity has a controller/model.
Workflow for a spinner to communicate with other fragments :
Register the spinner listener in Frag1
Register a data listener from Frag2 in Activity
OnItemSelected from Frag1 prevent Activity from the Spinner value change
Activity received the spinner change value
Activity call Frag2 listener to prevent Frag2 of the spinner change
Frag2 receive spinner change, do your stuff
Here is a litle schema
I would base everything on an event bus like Otto. IMHO, Fragments were meant to be decoupled from hosting activities and such, but all the interfaces and callbacks end up creating spaghetti code. Otto lets you post event on a common bus -- the receiver doesn't need to be tied to the sender via some listener/callback mechanism. Plus, it works great in conjunction with dependency injection, see Dagger.
Is it possible to user View pager without fragments. I google it, and all examples use fragments for view pager. I want to pager load only one item from my list, so I want to ask is it possible. Here is my code for main activity, and I want to use UpdateDisplay for viewpager. Any suggestions.
public class MainActivity extends Activity implements OnClickListener{
private Button prev, next;
private TextView tv;
private int number = 0;
private ArrayList<Integer> numbers;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (Button) findViewById(R.id.prevButton);
prev.setOnClickListener(this);
next = (Button) findViewById(R.id.nextButton);
next.setOnClickListener(this);
numbers = new ArrayList<Integer>();
for (int i=0;i<5;i++){
numbers.add(i);
Log.i("Sljedece elemente dodaje u listu", String.valueOf(i));
}
tv = (TextView) findViewById(R.id.rezultatTextView);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
updateDIsplay(number);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.prevButton:
number--;
if (number==-1){
number = 4;
}
updateDIsplay(number);
break;
case R.id.nextButton:
number++;
if (number==5){
number = 0;
}
updateDIsplay(number);
break;
}
}
private void updateDIsplay(int z){
tv.setText(String.valueOf(numbers.get(z)));
}
private class MyPagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return numbers.size();
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return false;
}
}
}
yes it possible. Use a PageAdapter. When instantiateItem is called, you can inflate/instantiate your view, and this to the container. E.g:
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
I build a project. but I'm having problems.
My project has page A , Page B
from Picture http://s20.postimg.org/5pupjbuyl/untitled.png
Page A is FrameLayout (id=layout) , in FrameLayout has LinearLayout and FrameLayout (id=content)
Page B is FrameLayout (id=pager) , in FrameLayout has Viewpager
I would take Framelayout (id=content) in page A containing FrameLayout(id = pager) in page B
(Notice : I try to minimize my code because It many line)
PageIndicatorActivity .java
public class PageIndicatorActivity extends Activity {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
..
..
ViewGroup Content = (ViewGroup)findViewById(R.id.layout);
ViewBookAdapter pager = new ViewBookAdapter(this);
Content.addView(pager.getView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,menu);
return true;
}}
pager.java
public class Pager extends PagerAdapter {
Activity activity;
private static String content[] = {"file:///android_asset/html/page1.html","file:///android_asset/html/page2.html"};
public Pager(Activity act) {
activity = act;
}
public int getCount() {
return content.length;
}
public Object instantiateItem(View collection, int position) {
WebView view = new WebView(activity);
view.loadUrl(content[position]);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}}
and ViewBookAdapter.java
class ViewBookAdapter {
Activity activity;
private LayoutInflater minflate;
private ViewPager myPager;
public ViewBookAdapter(Activity act){
activity = act;
myPager = (ViewPager)act.findViewById(R.id.viewPager);
Pager p = new Pager(act);
myPager.setAdapter(p); // <--- THIS PROBLEM ---
}
public View getView(){
LayoutInflater minflate = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = minflate.inflate(R.layout.pager, null);
return v;
}}
I have a probleam at myPager.setAdapter(p);
Android Report Bug is NullPointerException
How to solve?
THANK YOU FOR ANSWER ^^
PS. sorry english .
This is happening because your Activity does not have the ViewPager in its layout. Its in the other layout. You will need to do setAdapter in getView()
Your current PageIndicatorActivity layout does not have a ViewPager. If you need to continue this way you have to move to Activity(Page B) and follow your implementation.