ViewPager with PagerAdapter Not working - android

I'm trying to show images from Drawable in view pager using PagerAdapter for that, I have written below code--
// Call to the PagerAdapter
public void showAwardsBadgesAlert()
{
// custom dialog
final Dialog dialog = new Dialog(context, R.style.MyAlertDlgTheme);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.awards_badges_dlg_layout);
dialog.setCanceledOnTouchOutside(false);
dialog.setCanceledOnTouchOutside(true);
ViewPager awardsBadgesPager = (ViewPager) dialog.findViewById(R.id.awardsBadgesPager);
AwardsBadgesAdapter awardsBadgesAdapter = new AwardsBadgesAdapter(context, feedObject.getAwardStatistics().getAwardsBdgesList());
awardsBadgesPager.setAdapter(awardsBadgesAdapter);
dialog.show();
}
// Below is my Adapter Class--
public class AwardsBadgesAdapter extends PagerAdapter
{
private Context context;
private ArrayList<AwardsBadges> awardsList;
public AwardsBadgesAdapter(Context context, ArrayList<AwardsBadges> awardsList)
{
this.context = context;
this.awardsList = awardsList;
}
#Override
public int getCount()
{
if(awardsList != null)
{
return awardsList.size();
}
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == object;
}
#Override
public Object instantiateItem(final View container, final int position)
{
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.awards_badges_dlg_item, null);
ImageView ivAwards = (ImageView) layout.findViewById(R.id.ivAwardsBadges);
AwardsBadges currBadge = awardsList.get(position);
if(currBadge.getImageName()!=null && currBadge.getImageName().equalsIgnoreCase("pink star diamond"))
{
Picasso.with(context).load(R.drawable.pinkstar).into(ivAwards);
}
else if(currBadge.getImageName()!=null && currBadge.getImageName().equalsIgnoreCase("tanzanite"))
{
Picasso.with(context).load(R.drawable.tanzanite).into(ivAwards);
}
else if(currBadge.getImageName()!=null && currBadge.getImageName().equalsIgnoreCase("painite"))
{
Picasso.with(context).load(R.drawable.painite).into(ivAwards);
}
else if(currBadge.getImageName()!=null && currBadge.getImageName().equalsIgnoreCase("taaffeite"))
{
Picasso.with(context).load(R.drawable.taaffeite).into(ivAwards);
}
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((View) object);
}
#Override
public float getPageWidth(int position)
{
return (0.33f);
}
}
// Below is my dialog xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awardsBadgesPager"
android:layout_width="match_parent"
android:layout_height="#dimen/sz_seventy"
android:layout_below="#+id/txtPlace"
android:layout_margin="10dp"
android:background="#color/tipstransperent"
android:padding="10dp"
android:visibility="visible" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
// Below is ViewPager Item xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<ImageView
android:id="#+id/ivAwardsBadges"
android:layout_width="#dimen/sz_fifty"
android:layout_height="#dimen/sz_fifty"
android:layout_centerInParent="true" />
</RelativeLayout>
// Below is the screen shot explaining currently how it is showing empty ViewPager--
When I debug the app everything seems fine but don't know why Images are not getting displayed in ViewPager. Please Help..

First, you should be overriding the instantiateItem() method with ViewGroup as the first parameter, not the one with View as the first parameter. The latter is deprecated.
Then, you need to add your inflated View to the container in the PagerAdapter's instantiateItem() method. Quoting the docs for the instantiateItem() method:
The adapter is responsible for adding the view to the container given here
Simply add container.addView(layout); to the instantiateItem() method, before the return statement.

((ViewPager) container).addView(layout);
Add above statement in your instantiateItem() method, before the return statement. This will surely help you.

Related

How to access component from another view in android

I have created a custom dialog and inside it i create a view page which both have different layout file. Method to show the dialog is in MainActivity.
I inflate a layout to my adapter class where i populate the content. In this layout there is a button. My question is "How can i access the button from the layout that i inflate in my adapter class from my MainActivity. The reason I want to do this is because I want to dismiss the dialog when the button is clicked.
Thanks.
Here is the code of what i have done so far.
MainActivity:
public void ShowPromoOverlay(){
promoOverlay = new Dialog(this);
promoOverlay.requestWindowFeature(Window.FEATURE_NO_TITLE);
promoOverlay.setContentView(R.layout.fragment_overlay);
final List<Promotion> pageArr = new ArrayList<>();
int maxcounter = 5;
if (promotionList.size() < maxcounter) {
maxcounter = promotionList.size();
}
for (int counter = 0; counter < maxcounter; counter++){
pageArr.add(promotionList.get(counter));
}
TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr);
cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
pager = promoOverlay.findViewById(R.id.overlayPager);
pager.setPageMargin(50);
pager.setAdapter(adapter);
com.viewpagerindicator.CirclePageIndicator indicator =
promoOverlay.findViewById(R.id.overlay_page_indicator);
indicator.setViewPager(pager);
indicator.setCurrentItem(0);
promoOverlay.show();
View inlcudeLayout = findViewById(R.id.my_custom_dialog_layout);
ImageView closeBtn = (ImageView) inlcudeLayout.findViewById(R.id.closeBtn);
closeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promoOverlya.dismiss();
}
});
}
fragment_overlay:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/fragment_over"
android:background="#color/bg_orange"
android:layout_width="match_parent"
android:layout_height="match_parent">
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/overlayPager">
<include layout="#layout/my_custom_dialog" />
</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>
<com.viewpagerindicator.CirclePageIndicator
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/overlay_page_indicator"
android:layout_alignParentBottom="true"
android:layout_marginBottom="70dp">
</com.viewpagerindicator.CirclePageIndicator>
</RelativeLayout>
my_custom_dialog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_custom_dialog_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<android.support.v7.widget.CardView
android:layout_width="310dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_marginTop="40dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp">
<ImageView
android:id="#+id/closeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_clear_grey_600_24dp"
android:layout_marginTop="7dp"
android:layout_marginRight="7dp"
android:elevation="5dp"
android:layout_gravity="right"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
TestPagerAdapter:
public class TestPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
List<Promotion> pageArr;
public TestPagerAdapter(Context context, List<Promotion> pageArr){
this.context = context;
this.pageArr = pageArr;
inflater = ((Activity) context).getLayoutInflater();
}
public TestPagerAdapter(Context context){
this.context = context;
inflater = ((Activity) context).getLayoutInflater();
}
#Override
public int getCount(){
return pageArr.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position){
View view = inflater.inflate(R.layout.my_custom_dialog, container,
false);
TextView prTitle = view.findViewById(R.id.title_pr);
TextView prDescription = view.findViewById(R.id.description_pr);
TextView readMoreBtn = view.findViewById(R.id.readMore);
view.setTag(position);
((ViewPager) container).addView(view);
final Promotion promotion = pageArr.get(position);
prTitle.setText(promotion.getTitle());
prDescription.setText(promotion.getDescription());
return view;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == ((View) o);
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
Nice question. You should have to use the interface. let's try this code.
public interface OnButtonClickListner {
public void OnButtonClick();
}
Now You need to pass this interface in the adapter. like this
TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr TestPagerAdapter adapter = new TestPagerAdapter(this,new OnButtonClickListner()
{
#Override
public void OnButtonClick() {
// dismiss dialog here
}
});
Now, You need to change the constructor of Viewpager adapter. like below:
public TestPagerAdapter(Context context, List<Promotion> pageArr,OnButtonClickListner listner){
this.context = context;
this.pageArr = pageArr;
this.onButtonClickListner=listner;
inflater = ((Activity) context).getLayoutInflater();
}
Now you just need to call this listener method from adapter like onButtonClickListner.OnButtonClick(); and the method of popup will call and you will easily dismiss the dialog. you may also pass the argument if you need to require to pass the position of view page.
Click event of read more button like below :
readMoreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClickListner.OnButtonClick();
}
});
Hope this will help you.
Happy coding.....

I can't add new items that i called from a different XMLs to the ViewPager

I need to show some layout groups from different XMLs as items of a ViewPager. I create 2 different layouts. I want to use card.xml 1 time, and use the other more than one. When i click on the view of card.xml, i will write a code to add a new credit_cards.xml's view. Here i add the first two layouts and i can see them on the viewpager. I'm trying to add new view by hand but i got errors. It's my first time working with viewpager so I am not sure where the problem is.
This is my activity.
public class MainActivity extends AppCompatActivity {
final Context mContext = this;
public List<View> mList = new ArrayList<>();
ViewPager pager;
ViewPagerAdapter adapter;
LinearLayout first, second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = LayoutInflater.from(getApplication()).inflate(R.layout.credit_cards, null);
first = (LinearLayout) view.findViewById(R.id.addNewCard);
second = (LinearLayout) view.findViewById(R.id.creditCard);
pager = (ViewPager) findViewById(R.id.viewpager);
mList.add(first);
adapter = new ViewPagerAdapter(mContext, mList);
adapter.addView(second,0);
pager.setAdapter(adapter);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
This is ViewPager.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.seray.myapplication.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:layout_marginBottom="1sp">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"/>
</RelativeLayout>
</RelativeLayout>
Adapter.
public class ViewPagerAdapter extends PagerAdapter {
public List<View> mList;
private final Context mContext;
LinearLayout first, second;
View mPrimaryItem;
public ViewPagerAdapter(Context mContext, List<View> mList){
this.mContext = mContext;
this.mList = mList;
}
#Override
public int getItemPosition(Object object) {
if (mList.contains((View) object)) {
return mList.indexOf((View) object);
} else {
return POSITION_NONE;
}
}
#Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (View) object;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public int getCount() {
return mList.size();
}
public void addView(View view, int index) {
mList.add(index, view);
notifyDataSetChanged();
}
public void removeView(int index) {
mList.remove(index);
notifyDataSetChanged();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View v = mList.get(position);
((ViewPager)container).addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}

Set image to ViewPager from List of Objects

I would like to make banner carousel. Instead of RecyclerView I choose to use ViewPager. I have a problems with adapter implementation:
public class BannerAdapter extends PagerAdapter {
List<Banner> bannerList;
Context context;
ImageView imageView;
public BannerAdapter(List<Banner> list, Context context) {
bannerList = list;
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View v = View.inflate(context, R.layout.fragment_home_layout, null);
imageView = (ImageView) v.findViewById(R.id.image);
Picasso.with(context).load(OpApp.IMAGEORGINAL + bannerList.get(position).getMobileImage() + ".jpg").placeholder(R.drawable.op_logo).into(imageView);
return v;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
}
#Override
public int getCount() {
return bannerList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
The image is not loaded to the ViewPager.
fragment_home_layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background">
<-- Other Views -->
<android.support.v4.view.ViewPager
android:id="#+id/home_banner_carousel"
android:layout_width="match_parent"
android:layout_height="#dimen/_150sdp"
android:adjustViewBounds="true"
>
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.view.ViewPager>
<-- Other Views -->
</FrameLayout>
Actual result:
Expected result:
Additional to this question, what you can suggest to achieve position indicator functionality ? I think about implements ViewPager.OnPageChangeListener but not sure with that.
I know how to implement 'ViewPager' using 'Fragments' but in my case I need to use 'List' instead of 'Fragments', and I'm confused with that.
P.S. Please don't minus my question, just comment what you don't like and what is wrong and I will try to edit it. I'm newbie here and in android. Anyway, Thank you!
Solution founded, I have changed adapter`s 2 methods and all is working!
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
Picasso.with(context).load(OpApp.IMAGEORGINAL + bannerList.get(position).getMobileImage() + ".jpg")
.placeholder(R.drawable.op_logo).into(imageView);
((ViewPager) container).addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}

Image slider using View Pager issue

I have an activity which contains a listView. Each item of the listView contains a swipeable set of images (which I have unsuccessfully tried to implement using a ViewPager).
My issue is this: when I try to implement a simple image slider using a view pager (i.e. Activity contains a ViewPager, and the View Pager's adapter supplies the images), the output is as expected, but if I try doing what I have mentioned in the previous paragraph (i.e. The Activity contains a listView and each item of the listView is a ViewPager which displays a swipeable set of images), I get a blank output. Please help me out! I have posted some code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.stylistDisplay);
//To keep things simple I am sending only one item of the list to the adapter
list.setAdapter(new StylistAdapter(Cart.getList().get(0), this));
}
static class StylistAdapter extends BaseAdapter {
Stylist stylistObj;
Context context;
LayoutInflater inflater;
public StylistAdapter(Stylist obj, Context context) {
this.stylistObj = obj;
this.context = context;
inflater = ((Activity)this.context).getLayoutInflater();
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return stylistObj;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = inflater.inflate(R.layout.stylist_photos_view_pager, null);
item = new ViewItem();
item.photosViewPager = (ViewPager) convertView.findViewById(R.id.photos_view_pager);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
PhotosAdapter adapter = new PhotosAdapter(context);
item.photosViewPager.setAdapter(adapter);
return convertView;
}
private class ViewItem {
ViewPager photosViewPager;
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.temp.customer.MainActivity">
<ListView
android:id="#+id/stylistDisplay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:background="#color/backGround"
android:padding="13.3dp"
android:clickable="true"
android:dividerHeight="5dp" />
</FrameLayout>
stylist_photos_view_pager
<RelativeLayout xmlns:android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/photos_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
PhotosAdapter.java
public class PhotosAdapter extends PagerAdapter {
private Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
public PhotosAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.stylist_individual_details, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.iv1);
imageView.setImageResource(GalImages[position]);
TextView textView1 = (TextView) viewItem.findViewById(R.id.tv1);
textView1.setText("hello world");
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
boolean temp = view == ((LinearLayout) object);
return temp;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((LinearLayout) object);
}
}
I've experienced similar issue, and have to say that it is a bad idea to use ViewPager as a listItem, since ViewPager is supposed to be used for fragments primarily.
I guess that your functionality should be similar to some horizontal pictures, on the main feed which is vertical. You can think of using horizontal scroll views which is a bit of a pain, but still more realistic to do that. You might also end up managing your own scrolling behavior, which might already be implemented by some libraries.
BUT I MIGHT BE WRONG!
This thread has a similar issue:
Placing ViewPager as a row in ListView
After reading around for a while I tried explicitly setting the height of the viewPager and its parent. This worked for me.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="200dip" >
</android.support.v4.view.ViewPager>
</LinearLayout>
I don't know if there is a better solution, but if you do get a better solution please comment!

ViewPagers and PagerAdapters

I am new to Android and am trying a sample application for showing ViewPagers in a Master-Detail Flow using custom PagerAdapters and FragmentStatePagerAdapters. My application has a list of dummy items managed by a SQLiteDatabase which contain a title String, a description String, a Boolean like status, and a list of images (I plan to implement them as downloading from String urls but presently I'm just trying with a single image resource). I am having two problems in the Detail View.
My intention is to use a ViewPager with a FragmentStatePagerAdapter to show the detail view, which consists of a ViewPager with a custom PagerAdapter for showing the list of images, TextView for title and description, a ToggleButton for the like status and a delete button for deleting items from the list.
Issues:
The ViewPager with the custom PagerAdapter does not display the image. It occupies the expected space and swipes performed on it also behave as expected. Only the image is not visible.
[RESOLVED] On using the delete button, I am able to delete the item from the database, and also update the Master View accordingly, but I am not able to update the Detail View, and the app crashes.
Here is my code:
Code that calls ItemDetailActivity.java
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(getContext(), ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_LIST_POSITION, holder.position);
getContext().startActivity(detailIntent);
}
ItemDetailActivity.java
public class ItemDetailActivity extends FragmentActivity {
static ItemDetailPagerAdapter idpa;
static ViewPager detailPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
idpa = new ItemDetailPagerAdapter(getSupportFragmentManager());
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
detailPager = (ViewPager) findViewById(R.id.item_detail_container);
detailPager.setAdapter(idpa);
detailPager.setCurrentItem(getIntent().getIntExtra(ItemDetailFragment.ARG_LIST_POSITION, 0));
}
}
activity_item_detail.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.trial.piclist.ItemDetailActivity"
tools:ignore="MergeRootFrame" />
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
public static final String ARG_LIST_POSITION = "list_index";
public static final String ARG_TWO_PANE = "is_two_pane";
int position = -1;
long id = -1;
boolean twoPane = false;
ViewPager pager;
private PicItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
twoPane = getArguments().getBoolean(ARG_TWO_PANE, false);
position = getArguments().getInt(ARG_LIST_POSITION, -1);
id = getArguments().getLong(ARG_ITEM_ID, -1);
if (id == -1)
id = ItemListFragment.getIdByPosition(position);
setmItem(id);
}
public void setmItem(long id) {
if (id >= 0) {
try {
ItemListActivity.lds.open();
mItem = ItemListActivity.lds.getById(id);
ItemListActivity.lds.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (mItem != null) {
List<String> pics = new ArrayList<String>();
pics.add("1");
pics.add("2");
pics.add("3");
pics.add("4");
pics.add("5");
mItem.setPics(pics);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
DetailViewHolder holder = new DetailViewHolder();
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),
inflater, position);
pager.setAdapter(adapter);
holder.position = getArguments().getInt(ARG_LIST_POSITION);
holder.ttv = (TextView) rootView.findViewById(R.id.item_title);
holder.dtv = (TextView) rootView.findViewById(R.id.item_detail);
holder.likeButton = (ToggleButton) rootView
.findViewById(R.id.item_like);
holder.deleteButton = (Button) rootView.findViewById(R.id.item_delete);
rootView.setTag(holder);
if (mItem != null) {
holder.ttv.setText(mItem.getTitle());
holder.dtv.setText(mItem.getDescription());
holder.likeButton.setChecked(mItem.getIsLiked());
holder.likeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.toggleLike(mItem.getId());
mItem.toggleIsLiked();
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.toggleLiked(position);
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.removeItem(mItem.getId());
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.remove(position);
ItemListActivity.idpa.notifyDataSetChanged();
// What do I do so that the FragmentStatePagerAdapter is
// updated and the viewpager shows the next item.
}
});
}
return rootView;
}
static private class DetailViewHolder {
TextView ttv;
TextView dtv;
ToggleButton likeButton;
Button deleteButton;
int position;
}
}
fragment_item_detail.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.trial.piclist.ItemDetailFragment" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="200dip">
</android.support.v4.view.ViewPager>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/item_title"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textIsSelectable="true" />
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/controls_layout" />
</TableRow>
<ScrollView
android:id="#+id/descScrollView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
</ScrollView>
</LinearLayout>
controls_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ToggleButton
android:id="#+id/item_like"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_gravity="right"
android:background="#android:drawable/btn_star"
android:gravity="center"
android:text="#string/like_list_item"
android:textOff="#string/empty_text"
android:textOn="#string/empty_text" />
<Button
android:id="#+id/item_delete"
style="?android:attr/buttonStyleSmall"
android:layout_width="30dip"
android:layout_height="30dip"
android:background="#android:drawable/ic_menu_delete"
android:text="#string/empty_text" />
</LinearLayout>
Custom PagerAdapter
ImagePagerAdapter.java
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
List<View> layouts = new ArrayList<>(5);
// Constructors.
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (layouts.get(position) != null) {
return layouts.get(position);
}
View layout = inflater.inflate(R.layout.detail_image,
((ViewPager) container), true);
try {
ImageView loadSpace = (ImageView) layout
.findViewById(R.id.detail_image_view);
loadSpace.setBackgroundColor(0x000000);
loadSpace.setImageResource(R.drawable.light_grey_background);
loadSpace.setAdjustViewBounds(true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
layout.setTag(images.get(position));
layouts.set(position, layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (((View) object).findViewById((view.getId())) != null);
}
}
FragmentPagerAdapter
ItemDetailPagerAdapter.java
public class ItemDetailPagerAdapter extends FragmentStatePagerAdapter {
public ItemDetailPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putLong(ItemDetailFragment.ARG_ITEM_ID, ItemListFragment.getIdByPosition(position));
args.putInt(ItemDetailFragment.ARG_LIST_POSITION, position);
args.putBoolean(ItemDetailFragment.ARG_TWO_PANE, ItemListActivity.mTwoPane);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
openDatabase();
int c = database.getCount();
closeDatabase();
return c;
}
#Override
public int getItemPosition(Object object) {
long mId = ((ItemDetailFragment) object).getmId();
int pos = POSITION_NONE;
openDatabase();
if (database.contains(mId)) {
pos = database.getPositionById(mId);
}
closeDatabase();
return pos;
}
}
Any help is much appreciated. Thanks :)
In your ItemDetailFragment, remove the viewpager from the holder, it should be directly into the returned view, something like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),inflater, position);
pager.setAdapter(adapter);
return rootView;
}
and the ViewHolder pattern should be applied inside your PagerAdapter.
In ImagePagerAdapter.java, correct the isViewFromObject method -
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (View) object);
}
This will correct the issue of the ImageView.
In ItemDetailPagerAdapter.java, override the getItemPosition method -
#Override
public int getItemPosition(Object object) {
int ret = POSITION_NONE;
long id = ((ItemDetailFragment) object).getId();
openDatabase();
if (databaseContains(id)) {
ret = positionInDatabase(id);
}
closeDatabase();
return ret;
}
On deleting call the FragmentStatePagerAdapter.NotifyDataSetChanged() method. This will make the Adapter update itself on deleting.
Although, the FragmentStatePagerAdapter uses a list of Fragments and of stored states to implement the adapter. That is also causing trouble. To remove that, implement your own list of Fragments.

Categories

Resources