Used ViewPager for images sliding, when clicking on each image must do an action, its different action from image to another,
I'm new to android development
so I try to add onClick listener to ViewPager, but I can't achieve it,
please any suggestion how to implement OnClickListener so when I click the first image will do action and when click the second image will do another action and so on for all images, I have it inside the view pager
thanks in advance.
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
ImageAdapter:
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.g,
R.drawable.h,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
intpadding=context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
To catch click events in ViewPager you have to override onTouchListener, since default implementation is not made to handle clicks
Your MainActivity should look something like this:
private ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager= (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
mViewPager.setAdapter(adapter);
final GestureDetector tapGestureDetector = new GestureDetector(this, new TapGestureListener());
mViewPager.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
}
private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mViewPager.getCurrentItem() == 0) {
//do your thing tied with first page
} else if (mViewPager.getCurrentItem() == 1) {
//do your thing tied with second page
} else if (mViewPager.getCurrentItem() == 2) {
//do your thing tied with third page
}
return super.onSingleTapConfirmed(e);
}
}
Try this:
#Override
public Object instantiateItem(View collection, final int pos) { //have
to make final so we can see it inside of onClick()
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.YOUR_PAGE, null);
page.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//this will log the page number that was click do your action
according to position
Log.i("TAG", "This page was clicked: " + pos);
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
Related
I'm trying to make a drag and drop from a custom slider.
The slider is in a viewPager and is shows Imageviews.
I don't know witch ID I should set to my longClickListener.
I tried the Imagview (swip_image_view) but it return null.
& it doesn't work with the viewpager.
Why is my longClickListener not working?
public class Activity_Kind extends Activity {
ViewPager viewPager;
CustomHorizontalSwip customHorizontalSwip;
private GridView gridDieren;
private ImageView bus;
private ImageView slider;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kies_dier);
gridDieren = (GridView) findViewById(R.id.gridSelectDieren);
text = (TextView) findViewById(R.id.kiesdiertext);
bus = (ImageView) findViewById(R.id.imageBus);
viewPager = (ViewPager) findViewById(R.id.viewPager);
customHorizontalSwip = new CustomHorizontalSwip(this);
viewPager.setAdapter(customHorizontalSwip);
viewPager.setLongClickable(true);
viewPager.setOnLongClickListener(longClickListener);
//slider = (ImageView) findViewById(R.id.swip_image_view);
//slider.setOnLongClickListener(longClickListener);
bus.setOnDragListener(dragListener);
}
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder myShadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, myShadowBuilder, v, 0);
return true;
}
};
View.OnDragListener dragListener = new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
int dragEvent = event.getAction();
switch (dragEvent) {
case DragEvent.ACTION_DRAG_ENTERED:
final View view = (View) event.getLocalState(); //Krijgt alle informatie van die view die wordt gedraged
if (view.getId() == R.id.imageBus);
text.setText("Werkt");
//gridDieren.addView(view);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
case DragEvent.ACTION_DROP:
break;
}
return true;
}
};
}
public class CustomHorizontalSwip extends PagerAdapter {
private int [] imageResources ={R.drawable.beer,R.drawable.bever, R.drawable.kip, R.drawable.leeuw, R.drawable.nijlpaard, R.drawable.poes
,R.drawable.ezel,R.drawable.hond, R.drawable.ooievaar, R.drawable.varken, R.drawable.wormpje};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomHorizontalSwip(Context c) {
ctx=c;
}
#Override
public int getCount() {
return imageResources.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
}
Your image swip_image_view is inside layout custom_swipe_dieren.xml. You should set onLongClickListener inside CustomHorizontalSwip -> instantiateItem() method like this :
public class CustomHorizontalSwip extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
imageView.setOnLongClickListener(longClickListener);
container.addView(itemView);
return itemView;
}
/* Declare and Initialise longClickListener in this file also */
/* Also do same for dragListener in this file */
}
This will work for you
Thanks
The ImageAdapter Class
public class ImageAdapter extends PagerAdapter implements AdapterView.OnItemClickListener {
Context context;
private int[] GalImages = new int[] {//array storing all images used in the 'slideshow' in the main menu
R.drawable.savedpageex,
R.drawable.ic_cdi_icon,
R.drawable.savedpageex,
R.drawable.ic_cdi_icon
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(R.dimen.abc_panel_menu_list_width);
imageView.setPadding(1, 1, 1, 1);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int clickedImage = GalImages[position];
}
}
In the MainActivity
ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
ImageAdapter adapter = new ImageAdapter(this);
wrappedAdapter = new InfinitePagerAdapter(adapter);
viewPager.setAdapter(wrappedAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
}
});
Right now, the pictures show up and they loop, I do need help getting the pictures to 'slide' at set time intervals, but the main issue is with setting up onClickListeners for each 'page'. Any help/advice?
You could add a switch statement inside of the onClickListener like this
switch(viewPager.getCurrentItem()){
case 0:
//stuff for first page
break;
case 1:
//stuff for second page
break;
}
...... etc.
or add a state to the viewpager to describe which "page" it is showing
and using that information do different things in the onClickListener
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an activity that has container that contain fragments and this fragment has other fragments.
Now I want this second or child fragment to access views in main activity, but it returns null pointer exception.
class:
public class ImageListFragment extends AbsListViewBaseFragment implements ObservableScrollViewCallbacks {
public static final int INDEX = 0;
android.support.design.widget.FloatingActionButton mFab;
#Bind(R.id.ic_call)
ImageView mIcCall;
#Bind(R.id.ic_email)
ImageView mIcEmail;
#Bind(R.id.ic_forum)
ImageView mIcForum;
FabToolbar mFabToolbar;
ObservableListView mObservableListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ImageAdapter(getActivity()));
final SubTaB mainActivity = (SubTaB)getActivity();
ButterKnife.bind(mainActivity);
//////////////// problem here
mFabToolbar = (FabToolbar) rootView.findViewById(R.id.fabtoolbar);
////////////////
getFragmentManager().findFragmentByTag("TAG");
// rootView.findViewById(R.id.fab);
mObservableListView = (ObservableListView)rootView.findViewById(android.R.id.list);
//
mObservableListView.setAdapter(this.listView.getAdapter());
mObservableListView.setScrollViewCallbacks(this);
mainActivity.mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mainActivity.getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
mainActivity.mFabToolbar.expandFab();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
private static class ImageAdapter extends BaseAdapter {
private static final String[] IMAGE_URLS = Constants.IMAGES;
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
ImageAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub) // تغيير الفيو قبل تحميل الصورة
.showImageForEmptyUri(R.drawable.ic_empty) // لما الصورة فاضية
.showImageOnFail(R.drawable.ic_error) // عند الفشل
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
.build();
}
#Override
public int getCount() {
return IMAGE_URLS.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options, animateFirstListener);
return view;
}
}
static class ViewHolder {
TextView text;
ImageView image;
}
#Override
public void onScrollChanged(int i, boolean b, boolean b1) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
Log.d("","Scroll scroll scroll");
if (scrollState == ScrollState.UP) {
mFabToolbar.slideOutFab();
} else if (scrollState == ScrollState.DOWN) {
mFabToolbar.slideInFab();
}
}
#OnClick(R.id.fab)
void onFabClick() {
mFabToolbar.expandFab();
}
#OnClick(R.id.call)
void onClickCall() {
iconAnim(mIcCall);
}
#OnClick(R.id.ic_email)
void onClickEmail() {
iconAnim(mIcEmail);
}
#OnClick(R.id.ic_forum)
void onClickForum() {
iconAnim(mIcForum);
}
private void iconAnim(View icon) {
Animator iconAnim = ObjectAnimator.ofPropertyValuesHolder(
icon,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f, 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f, 1f));
iconAnim.start();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
It is not good practise to find and control a view in this way. Views can easily become detached from activities and cause unexpected exceptions.
You should rather look at using callbacks to communicate between fragments and activities if required. That way, it also keeps your code in the correct places - so the activity is the only one touching its own views and the fragment also only touches its own views. It merely tells the activity (via callbacks) that something has happened that the activity might want to know about. It also ensures that the fragments are completely self contained and can be easily reused.
You can read about how to implement callbacks here: http://developer.android.com/training/basics/fragments/communicating.html
Use EventBus to communicate between the activity and the fragment. riggarro suggestion is the correct way. But you can also able to update the base activity views using the EventBus.
For example we need to update a TextView text in a activity from the fragment, follow the steps.
First you need to add the following library as dependency to your project in build.gradle of your app.
compile 'de.greenrobot:eventbus:2.4.0'
First you need to create a Event Object class to communicate between the fragment and activity like below.
public class UpdateTextEvent {
private String sampleTextValue;
public UpdateTextEvent(String textValue) {
this.sampleTextValue = textValue;
}
public String getTextValue() {
return sampleTextValue;
}
}
You need to post a event to the event bus in the fragment to update the TextView in the activity.
public class TestingFragment extends Fragment{
private EventBus bus = EventBus.getDefault()
public TextingFragment(){}
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.sample_activity, parent, false);
...
Button b1 = (Button) v.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//trigger a update to the activity
bus.post(new UpdateTextEvent("testing"));
}
});
}
}
After that you need to register the bus with the callback of the event in the activity like below.
public class MainActivity extends Activity{
private EventBus bus = EventBus.getDefault();
private TextView textView;
#Override
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
....
// The textview going to be updated on posting the event
textView = (TextView) findViewById(R.id.text1);
bus.register(this);
}
public void onEvent(UpdateTextEvent event){
textView.setText(event.getTextValue());
}
}
In this above example the onEvent method will be called when you post a event from the fragment..
Hope it will help you.
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}
I have a ViewPagerActivity with two views. I want to register a context menu, different for each view. I tried a few things (registerForContextMenu()) but I always ended up with both views behaving like the second one. Any ideas?
public class ViewPagerActivity extends UomeActivity {
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
refreshAdapter();
}
private class ViewPagerAdapter extends PagerAdapter {
private final List<Transaction> accountTransactions;
private final List<User> accountUsers;
public ViewPagerAdapter() {
// initialize lists
}
#Override
public Object instantiateItem(View collection, int viewPosition) {
View layout;
ListView listView;
switch (viewPosition) {
case 0:
layout = LayoutInflater.from(getApplicationContext()).inflate(
R.layout.list_account_paired_transactions, null);
List<PairedTransaction> pairedTransactions = getPairedTransactions();
adapter = new AccountPairedTransactionItemAdapter(ViewPagerActivity.this,
R.layout.list_account_paired_transactions, pairedTransactions);
listView = (ListView) layout.findViewById(android.R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// do something
}
});
registerForContextMenu(listView);
break;
case 1:
layout = LayoutInflater.from(getApplicationContext()).inflate(
R.layout.list_account_transactions, null);
initViewPagerInfo(layout, R.string.paired_transactions,
R.string.all_account_transactions, R.string.empty, viewPosition);
adapter = new TransactionItemAdapter(ViewPagerActivity.this,
R.layout.list_account_transactions, accountTransactions,
new UserDaoImpl(
getApplicationContext()));
listView = (ListView) layout.findViewById(android.R.id.list);
registerForContextMenu(listView);
break;
default:
throw new IllegalArgumentException("Unsupported number of views.");
}
listView.setAdapter(adapter);
listView.setDivider(new ColorDrawable(R.color.list_separator));
listView.setDividerHeight(1);
listView.setBackgroundColor(Color.WHITE);
listView.setCacheColorHint(Color.WHITE);
((ViewPager) collection).addView(layout);
return layout;
}
// omitted
}
#Override
protected void onResume() {
refreshAdapter();
super.onResume();
}
private void refreshAdapter() {
viewPagerAdapter = new ViewPagerAdapter();
viewPager = findById(R.id.view_pager);
viewPager.setAdapter(viewPagerAdapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.add(R.string.show_info);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO: toast which object has been selected
}
}
The problem is that both views are instantiated at the same time (filling the viewpager). Setting the onRegisterForContextMenu in the second view is overwriting it from the first view.
A possible solution would be to check to see what view is visible in you onContextItemSelected method.