I have created an automatic image slider using custom ViewPager Now i want to know how to stop the automatic sliding of images on touch and start the slider again from it was left when touch is released.
Here is my CustomViewPager.java :-
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled = true;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
}
Here is ImageAdapter.java :-
public class SlidingImage_Adapter extends PagerAdapter {
Context context;
int images[];
LayoutInflater inflater;
public SlidingImage_Adapter(Context context, int images[]) {
this.context = context;
this.images = images;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = inflater.inflate(R.layout.sliding_images, container, false);
final ImageView imageView = (ImageView) itemView
.findViewById(R.id.image);
imageView.setImageResource(images[position]);
container.addView(itemView, 0);
return itemView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
Here is Fragment.java where i am using this CustomViewPager :-
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
TextView tv_slider, tv_button;
RelativeLayout dummyView;
CustomViewPager mViewPager;
Timer timer;
final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
int images[] = {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
SlidingImage_Adapter imageAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
tv_slider=(TextView)v.findViewById(R.id.tv_slider);
tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
tv_button=(TextView)v.findViewById(R.id.tv_button);
tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));
mViewPager = (CustomViewPager) v.findViewById(R.id.pager);
imageAdapter = new SlidingImage_Adapter(getActivity(),images);
mViewPager.setAdapter(imageAdapter);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mViewPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
CirclePageIndicator indicator = (CirclePageIndicator)
v.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(3 * density);
NUM_PAGES =images.length;
// Pager listener over indicator
indicator.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
switch (pos){
case 0:
tv_slider.setText(getString(R.string.es_content));
break;
case 1:
tv_slider.setText(getString(R.string.dm_content));
break;
case 2:
tv_slider.setText(getString(R.string.ev_content));
break;
case 3:
tv_slider.setText(getString(R.string.it_content));
break;
case 4:
tv_slider.setText(getString(R.string.md_content));
break;
case 5:
tv_slider.setText(getString(R.string.seo_content));
break;
case 6:
tv_slider.setText(getString(R.string.sd_content));
break;
case 7:
tv_slider.setText(getString(R.string.wd_content));
break;
}
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
return v;
}
According to this documentation, the onTouchEvent which you have already overridden is where to look at.
Now instead of calling super.onTouchEvent(event) again as you did in your method. implement your own custom action. by calling super, you're accepting the default behavior.
this is my example code it's working good =>
public class MainActivity extends AppCompatActivity {
final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000;
int currentPage = 0;
public Timer timer;
public Timer swipeTimer;
public static boolean startSlider = true;
public TextView textView;
public LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
layout = (LinearLayout) findViewById(R.id.layout);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == 6) {
currentPage = 0;
}
currentPage++;
textView.setText(String.valueOf(currentPage));
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
if (startSlider){
handler.post(Update);
}
}
}, DELAY_MS, PERIOD_MS);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (startSlider){
startSlider = false;
}else {
startSlider = true;
}
}
});
}
}
i have found a third party library "Library Link" and it has built-in methods for starting and stopping the automatic scrolling.
Related
I'm displaying three recyclerviews inside a fragment. I have recently changed my implementation so I can display some feature on a dropdown menu while long pressing on an item inside one of the three recyclerview.
Since then my app treats the click event on the two first recyclerview incorrectly (out of bound issue) and I know from debbuging that those click events are managed onely by the third adapter.
Here's my fragment code displaying the three recyclerviews:
public class ActivityFragment extends Fragment {
private int Index;
private ForecastRecyclerAdapter FirstView_Adapter;
private ForecastRecyclerAdapter SecondView_Adapter;
private ForecastRecyclerAdapter ThirdView_Adapter;
private CardView FirstCard, SecondCard, ThirdCard;
private LinearLayout SeparatorLayout1, SeparatorLayout2;
private ArrayList<MainViewArrayListRecycler> ListFirstView;
private ArrayList<MainViewArrayListRecycler> ListSecondView;
private ArrayList<MainViewArrayListRecycler> ListThirdView;
public static ActivityFragment newInstance(int Index) {
Bundle args = new Bundle();
ActivityFragment fragment = new ActivityFragment();
args.putInt(GETINDEX, Index);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mview = inflater.inflate(R.layout.fragment_mainactivity_forecast, container, false);
if (getArguments() != null) {
Index = getArguments().getInt(GETINDEX);
}
ViewModel viewModel = new ViewModelProvider(this).get(ViewModel.class);
viewModel.getInfo().observe(getViewLifecycleOwner(), Informations -> {
if (Informations != null) {
FillUpArray(Informations.get(Index));
}
});
FirstCard = mview.findViewById(R.id.FirstCard);
SecondCard = mview.findViewById(R.id.SecondCard);
ThirdCard = mview.findViewById(R.id.ThirdCard);
SeparatorLayout1 = mview.findViewById(R.id.SeparatorLayout1);
SeparatorLayout2 = mview.findViewById(R.id.SeparatorLayout2);
RecyclerView FirstView = mview.findViewById(R.id.First_Inside_Recycler);
RecyclerView SecondView = mview.findViewById(R.id.Second_Inside_Recycler);
RecyclerView ThirdView = mview.findViewById(R.id.Third_Inside_Recycler);
FirstView_Adapter = new ForecastRecyclerAdapter();
SecondView_Adapter = new ForecastRecyclerAdapter();
ThirdView_Adapter = new ForecastRecyclerAdapter();
FirstView.setLayoutManager(new LinearLayoutManager(getContext()));
SecondView.setLayoutManager(new LinearLayoutManager(getContext()));
ThirdView.setLayoutManager(new LinearLayoutManager(getContext()));
FirstView.setAdapter(FirstView_Adapter);
SecondView.setAdapter(SecondView_Adapter);
ThirdView.setAdapter(ThirdView_Adapter);
FirstView_Adapter.setOnItemClickListener(new ActivityFragmentAdapter.ActivityFragmentAdapterListener() {
#Override
public void onFirstClick(int position) {
//...
}
#Override
public void onSecondClick(int position) {
//...
}
#Override
public void onThirdClick(int position, boolean isChecked) {
if (isChecked) {
//...
}
}
});
SecondView_Adapter.setOnItemClickListener(new ActivityFragmentAdapter.ActivityFragmentAdapterListener() {
#Override
public void onFirstClick(int position) {
//...
}
#Override
public void onSecondClick(int position) {
//...
}
#Override
public void onThirdClick(int position, boolean isChecked) {
if (isChecked) {
//...
}
}
});
ThirdView_Adapter.setOnItemClickListener(new ActivityFragmentAdapter.ActivityFragmentAdapterListener() {
#Override
public void onFirstClick(int position) {
//...
}
#Override
public void onSecondClick(int position) {
//...
}
#Override
public void onThirdClick(int position, boolean isChecked) {
if (isChecked) {
//...
}
}
});
return mview;
}
private void FillUpArray(Information Info) {
/* Fill up the different arraylist and call setData frome the adapter */
}
}
Here's the recycler adapter class used:
public class ActivityFragmentAdapter extends RecyclerView.Adapter<ActivityFragmentAdapter.InsideRecyclerHolder> {
private ArrayList<MainViewArrayListRecycler> mRecyclerArrayListType;
private static ActivityFragmentAdapterListener mListener;
private String mUnit;
private int mAverageDistance;
private int mCurrentDistance;
private int mPeriodInterval;
public void setData(ArrayList<MainViewArrayListRecycler> RecyclerArrayListType) {
mRecyclerArrayListType = RecyclerArrayListType;
notifyDataSetChanged();
}
#NonNull
#Override
public InsideRecyclerHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater myInflater = LayoutInflater.from(parent.getContext());
View myOwnView = myInflater.inflate(R.layout.forecast_recycler, parent, false);
return new InsideRecyclerHolder(myOwnView, mListener);
}
#Override
public void onBindViewHolder(#NonNull InsideRecyclerHolder holder, int position) {
MainViewArrayListRecycler currentItem = mRecyclerArrayListType.get(position);
String tmpConcatDistance;
holder.t1.setText(currentItem.getTitle()));
holder.t2.setText(currentItem.getText());
}
#Override
public int getItemCount() {
return mRecyclerArrayListType.size();
}
public static class InsideRecyclerHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
final TextView t1;
final TextView t2;
final CheckBox cb1;
public InsideRecyclerHolder(#NonNull View itemView, final ForecastRecyclerAdapterListener listener) {
super(itemView);
t1 = itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
cb1 = itemView.findViewById(R.id.cb1);
cb1.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (listener != null) {
int position = getBindingAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onThirdClick(position, isChecked);
cb1.setChecked(false);
}
}
});
itemView.setOnCreateContextMenuListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getBindingAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onFirstClick(position);
return true;
case 2:
mListener.onSecondClick(position);
return true;
}
}
}
return false;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle(R.string.dropdown_menu_title);
MenuItem firstItem = menu.add(Menu.NONE, 1, 1, R.string.dropdown_menu_firstItem);
MenuItem secondItem = menu.add(Menu.NONE, 2, 2, R.string.dropdown_menu_secondItem);
firstItem.setOnMenuItemClickListener(this);
secondItem.setOnMenuItemClickListener(this);
}
}
public interface ActivityFragmentAdapterListener {
void onFirstClick(int position);
void onSecondClick(int position);
void onThirdClick(int position, boolean isChecked);
}
public void setOnItemClickListener(ActivityFragmentAdapterListener listener) {
mListener = listener;
}
}
What can be the issue ?
I've a image slider made with the help of ViewPager. I want to show different toast messages when clicked in different images loaded by ViewPager, how can i do that?
this my activity where image slider is shown:
public class MainActivity extends AppCompatActivity{
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN=
{R.drawable.benz2, R.drawable.benz2,
R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
and this is the adapter of the viewpager:
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public MyAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
I tried to make by adding
if (currentPage==1){
Toast.makeText(this, "page 1", Toast.LENGTH_SHORT).show();
}
in init() but it didn't work.
From what i could understand you need to display the toast when clicking on the image in each page of a ViewPager in which case an easy way is to add an onClickListener to your ImageView inside your adapter's instantiateItem method. So you should change/replace your method with this:
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup view, final int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), "page "+position, Toast.LENGTH_SHORT).show();
}
});
view.addView(myImageLayout, 0);
return myImageLayout;
}
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
Log.i("TAG", "This page was clicked: " + pos);
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
Hope this will work!
Make Image click interface in adapter class
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
MyClassImage myClassImage;
public interface MyClassImage{
void imageClick(String id);
}
public ViewPagerAdapter(Context context, ArrayList<Integer> images,MyClassImage myClassImage) {
this.context = context;
this.images=images;
this.myClassImage=myClassImage;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.z_slide_pager_item, view, false);
ImageView myImage = (ImageView) myImageLayout.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
final int id=images.get(position);
final String imgId=String.valueOf(id);
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myClassImage.imageClick(imgId);
}
});
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
and implement it on your MainActivity class
public class MainActivity extends AppCompatActivity implements MyAdapter.MyClassImage {
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.benz2, R.drawable.benz2, R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray,this));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
#Override
public void imageClick(String id) {
Toast.makeText(this, "page "+id, Toast.LENGTH_SHORT).show();
}
Hope it will be helpful to you.
Thanks.
I am doing an app which auto-scrolls images, at the bottom of the screen there is a static layout, which I need to display the value of images that have already passed (i.e. position).
I get the correct value of images passed by implementing :
int position = holder.getAdapterPosition();
in the RecyclerViewListAdapter.java
now I need to display this value in the RecyclerViewListActivity.java
on a text view at the static layout beneath the Recycler view?
public class RecyclerViewListAdapter extends RecyclerView.Adapter {
Context context;
List<Data> dataList;
private SharedPreferences preferences;
public RecyclerViewListAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.mImage.setImageResource(dataList.get(position).getImage());
holder.mImage.setImageResource(dataList.get(position).getImage());
**int position = holder.getAdapterPosition();**
}
#Override
public int getItemCount() {
if (dataList == null || dataList.size() == 0)
return 0;
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mNumberText,mText;
ImageView mImage;
LinearLayout mLinearLayout;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.quran_page);
mLinearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
}
}
}
public class RecyclerViewListActivity extends AppCompatActivity {
RecyclerView mListRecyclerView;
ArrayList<Data> dataArrayList;
RecyclerViewListAdapter recyclerViewListAdapter ;
Runnable updater;
private boolean isTouch = false;
TextViewRemaining;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_list);
final TextView TextViewRemaining = (TextView) findViewById(R.id.TextViewRemaining);
**TextViewRemaining.setText("Position: "+position);**
initializeView();
mListRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mListRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(RecyclerViewListActivity.this, "Long press on position :" + position,
Toast.LENGTH_LONG).show();
}
}));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
//#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void initializeView()
{
mListRecyclerView = (RecyclerView) findViewById(R.id.vR_recyclerViewList);
setValues();
}
private void setValues(){
prepareData();
recyclerViewListAdapter = new RecyclerViewListAdapter(RecyclerViewListActivity.this,dataArrayList);
mListRecyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewListActivity.this)); // original
mListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mListRecyclerView.setHasFixedSize(false);
mListRecyclerView.setAdapter(recyclerViewListAdapter);
recyclerViewListAdapter.notifyDataSetChanged();
final int speedScroll = 2000; //default is 2000 it need to be 30000
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
// boolean flag = true;
#Override
public void run() {
boolean x=true;
// while(x) {
if (count < recyclerViewListAdapter.getItemCount()) {
if (count == recyclerViewListAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
}
if (flag) count++;
// else count--;
mListRecyclerView.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable,speedScroll);
}
private void prepareData(){
dataArrayList = new ArrayList<>();
Data data1 = new Data();
data1.setImage(R.drawable.p1);
dataArrayList.add(data1);
Data data2 = new Data();
data2.setImage(R.drawable.p2);
dataArrayList.add(data2);
Data data3 = new Data();
data3.setImage(R.drawable.p3);
dataArrayList.add(data3);
Data data4 = new Data();
data4.setImage(R.drawable.p4);
dataArrayList.add(data4);
Data data5 = new Data();
data5.setImage(R.drawable.p5);
dataArrayList.add(data5);
}
}
So, How can I show the position value on textView in a real-time, as position is a dynamic value, I expect the output on the textView to change as the images passed to the top.
Many Thanks in advance.
This how I solve my problem:
I save the position value in a power Preference(an easier version of shared Preferences)-many thanks to:
Ali Asadi(https://android.jlelse.eu/powerpreference-a-simple-approach-to-store-data-in-android-a2dad4ddc4ac)
I use a Thread that updates the textview every second-many thanks to:
https://www.youtube.com/watch?v=6sBqeoioCHE&t=149s
Thanks for all.
When I extend an Activity this works fine, but when extending ActivityFragment I get an error:
unable to resolve constructor
At this line: BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this). I'm just fetching the image from a URL and displaying it in an image slider. If anyone knows any links or tutorials feel free to suggest me. Thanks.
HomeActivity.java
public class HomeActivity extends Fragment {
private String[] paths = {"http://reviewsimpact.com/wp-content/uploads/2016/04/Patanjali-products-list-1024x385.png",
"https://4.bp.blogspot.com/-3-qgzGwoQ3o/Vuqb1a0g6RI/AAAAAAAAATc/FZjOTm0VUBgXsw3VnWz3RorARUUUgl32g/s1600/Baba%2BRamdev%2BPatanjali%2BProducts%2BList%2Bwith%2BPrice%2Blatest%2B-%2BTipsmonk.jpg",
"http://patanjalistores.com/wp-content/uploads/2015/08/maxresdefault-1920x692.jpg",
"https://aos.iacpublishinglabs.com/question/aq/700px-394px/poems-fruits-vegetables_8d6a91e11da7d63.jpg?domain=cx.aos.ask.com",
"https://i.ytimg.com/vi/2IVR8BrUESQ/maxresdefault.jpg"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
AutoScrollViewPager mViewPager = (AutoScrollViewPager) v.findViewById(R.id.viewPager);
mViewPager = (AutoScrollViewPager)v.findViewById(R.id.viewPager);
BaseViewPagerAdapter<String> adapter = new BaseViewPagerAdapter<String>(this) {
#Override
public void loadImage(ImageView view, int position, String url) {
Picasso.with(getActivity().getApplicationContext()).load(url).into(view);
}
#Override
public void setSubTitle(TextView textView, int position, String s) {
textView.setText("");
}
};
mViewPager.setAdapter(adapter);
adapter.add(initData());
return v;
}
private List<String> initData() {
List<String> data = new ArrayList<>();
Picture picture ;
for (int i = 0 ; i < paths.length ;i++){
data.add(paths[i]);
}
return data;
}
}
BaseBaseViewPagerAdapter.java
public abstract class BaseViewPagerAdapter<T> extends PagerAdapter implements ViewPager.OnPageChangeListener{
private List<T> data = new ArrayList<>();
private Context mContext;
private AutoViewPager mView;
private OnAutoViewPagerItemClickListener listener;
public BaseViewPagerAdapter(List<T> t) {
this.data = t;
}
public BaseViewPagerAdapter(Context context, OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.listener = listener;
}
public BaseViewPagerAdapter(Context context, List<T> data) {
this.mContext = context;
this.data = data;
}
public BaseViewPagerAdapter(Context context, List<T> data,OnAutoViewPagerItemClickListener listener) {
this.mContext = context;
this.data = data;
this.listener = listener;
}
public void init(AutoViewPager viewPager,BaseViewPagerAdapter adapter){
mView = viewPager;
mView.setAdapter(this);
mView.addOnPageChangeListener(this);
if (data == null || data.size() == 0){
return;
}
//设置初始为中间,这样一开始就能够往左滑动了
int position = Integer.MAX_VALUE/2 - (Integer.MAX_VALUE/2) % getRealCount();
mView.setCurrentItem(position);
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
public void setListener(OnAutoViewPagerItemClickListener listener) {
this.listener = listener;
}
public void add(T t){
data.add(t);
notifyDataSetChanged();
mView.updatePointView(getRealCount());
}
public void add(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.addAll(list);
notifyDataSetChanged();
mView.start();
mView.updatePointView(getRealCount());
}
public void init(List<T> list){
if (data == null) {
data = new ArrayList<>();
}
data.clear();
data.addAll(list);
notifyDataSetChanged();
if (!mView.isStart()) {
mView.start();
mView.updatePointView(getRealCount());
}
}
#Override
public int getCount() {
return (data == null || data.size() == 0 ) ? 0 : Integer.MAX_VALUE;
}
public int getRealCount(){
return data == null ? 0 : data.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView view = (ImageView) LayoutInflater.from(mContext)
.inflate(R.layout.imageview,container,false);
loadImage(view,position, data.get(position % getRealCount()));
container.addView(view);
//设置标题(不知道为什么标题跟图片对不上,所以做了如下处理,有大神看到帮忙看看。。。)
if (mView.getSubTitle() != null){
if (position == 0){
setSubTitle(mView.getSubTitle(),position,data.get((getRealCount() - 1)));
}else {
setSubTitle(mView.getSubTitle(),position,data.get((position - 1) % getRealCount()));
}
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemClick(position % getRealCount(),data.get(position % getRealCount()));
}
}
});
return view;
}
public abstract void loadImage(ImageView view,int position,T t);
public abstract void setSubTitle(TextView textView,int position,T t);
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mView.onPageSelected(position % getRealCount());
}
#Override
public void onPageScrollStateChanged(int state) {
}
public interface OnAutoViewPagerItemClickListener<T> {
void onItemClick(int position,T t);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeActivity();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
Currently I'm changing Tabs from NavigationDrawer but it's not a right way and it takes too long to change tabs from NavigationDrawer becuase I'm replacing Main Fragment of Tabs each time and I don't want it. For more
NavigationDrawerAdapter.java
public class NavDrawerListAdapter extends BaseAdapter {
public Context context;
public MainActivity activity;
public MainTabFragment fragment;
int currentSelectedPostion;
LayoutInflater mInflater;
TextView tv_signup;
SharedPreferences share;
boolean cbc = false;
String fis = "", las = "";
int group_id = 0;
private String[] titles;
private int[] images;
private int[] selectedposition;
public NavDrawerListAdapter(Context context, int[] selectedposition, boolean cb, String fis, String las) {
this.context = context;
this.images = images;
this.cbc = cb;
this.fis = fis;
this.las = las;
share = context.getSharedPreferences("sharePref", 0);
group_id = share.getInt("group_id", 0);
this.selectedposition = selectedposition;
mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 1;
}
#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) {
if (convertView == null) {
convertView = mInflater.inflate(com.cws.advisorymandi.R.layout.drawer_list_item, null);
}
LinearLayout ll_contact_us = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.contact_item);
RelativeLayout ll_login = (RelativeLayout) convertView.findViewById(com.cws.advisorymandi.R.id.signup_item);
LinearLayout ll_equity = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.equity_item);
LinearLayout ll_indices = (LinearLayout) convertView.findViewById(com.cws.advisorymandi.R.id.indices_item);
if (cbc) {
tv_signup.setText("Welcome " + fis + " " + las);
tv_logout.setVisibility(View.VISIBLE);
tv_edit.setVisibility(View.VISIBLE);
}
ll_equity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.getInstance().displayView(3, 0, 0);
}
});
ll_indices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.getInstance().displayView(3, 0, 1);
}
});
});
return convertView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
public ListView mDrawerList;
NavDrawerListAdapter adapter;
public static MainActivity getInstance() {
return sMainActivity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.cws.advisorymandi.R.layout.activity_main)
mDrawerList = (ListView) findViewById(com.cws.advisorymandi.R.id.list_slidermenu);
adapter = new NavDrawerListAdapter(getApplicationContext(), selectedposition, cb, firstName, lastName);
mDrawerList.setAdapter(adapter);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
public int displayView(int position, int position2, int position3) {
// update the main content by replacing fragments
first_position = position;
second_position = position2;
third_position = position3;
fragment = null;
switch (position) {
case 0:
sharedPreferences = getSharedPreferences("sharePref", 0);
cb = sharedPreferences.getBoolean("ConfirmLogin", false);
if (cb) {
} else new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fragment = new LoginActivity();
changeFragments3();
}
}, 150);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 3:
// fragment = new MainTabFragment();
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {*/
fragment = new MainTabFragment();
changeFragments();
/*}
}, 150);
mDrawerLayout.closeDrawer(mDrawerList);*/
break;
}
return 0;
}
}
Note: I created each drawer item without using an array or arrayList so onItemClickListener isn't also working in it.