OnClickListener in PagerAdapter - java

I have an Activity that uses a ViewPager, within this ViewPager is a TouchImageView (an ImageView that detects gestures and zooms/moves accordingly).
Now I want to change some things in the UI whenever the image is clicked, but because the TouchImageView is declared in the PagerAdapter I can't reach it and if I would setup something on the side of the PagerAdapter I couldn't reach the UI components I want to change (I would also like to use the same adapter somewhere else in my app when I got this working). I've tried setting up an onClickListener on the ViewPager itself, but that doesn't trigger. Now I really don't know what to do.
Here is the adapter:
public class FullScreenImageAdapter extends PagerAdapter {
private ArrayList<MediaFile> images;
public FullScreenImageAdapter( ArrayList<MediaFile> images) {
this.images = images;
}
#Override
public int getCount() {
return images.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
Bitmap bitmap = BitmapFactory.decodeFile(images.get(position).getPath());
img.setImageBitmap(bitmap);
container.addView(img, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
And here is the method that interacts with it (in the ProjectOverviewActivity class):
private void viewPicture(final int position) {
View decorView = getWindow().getDecorView();
statusBarVisibility = decorView.getSystemUiVisibility();
// Hide the status bar.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
FullScreenImageAdapter imageAdapter = new FullScreenImageAdapter(mediaFiles);
final ViewPager viewPager = (ViewPager) findViewById(R.id.image_pager);
viewPager.setAdapter(imageAdapter);
viewPager.setCurrentItem(position);
View fancyBox = findViewById(R.id.fancyBox);
fancyBox.setVisibility(View.VISIBLE);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View btnClose = findViewById(R.id.fancyBoxBtnClose);
View btnPrev = findViewById(R.id.fancyBoxBtnPrev);
View btnNext = findViewById(R.id.fancyBoxBtnNext);
if (overlayButtonsVisible) {
btnClose.setVisibility(View.GONE);
btnPrev.setVisibility(View.GONE);
btnNext.setVisibility(View.GONE);
} else {
btnClose.setVisibility(View.VISIBLE);
if (viewPager.getCurrentItem() > 0) {
btnPrev.setVisibility(View.VISIBLE);
}
if (viewPager.getCurrentItem() < (mediaFiles.size() - 1)) {
btnNext.setVisibility(View.VISIBLE);
}
}
overlayButtonsVisible = !overlayButtonsVisible;
}
});
View fancyBoxBtnClose = findViewById(R.id.fancyBoxBtnClose);
final View fancyBoxBtnPrev = findViewById(R.id.fancyBoxBtnPrev);
final View fancyBoxBtnNext = findViewById(R.id.fancyBoxBtnNext);
fancyBoxBtnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View decorView = getWindow().getDecorView();
// Show the status bar.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
decorView.setSystemUiVisibility(statusBarVisibility);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, statusBarVisibility);
}
findViewById(R.id.fancyBox).setVisibility(View.GONE);
setViewAndChildrenEnabled(findViewById(R.id.layoutProjectOverview), true);
overlayButtonsVisible = false;
}
});
fancyBoxBtnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
if (viewPager.getCurrentItem() == 0) {
fancyBoxBtnPrev.setVisibility(View.GONE);
}
}
});
fancyBoxBtnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
if (viewPager.getCurrentItem() == (mediaFiles.size() - 1)) {
fancyBoxBtnNext.setVisibility(View.GONE);
}
}
});
}

You can try this
Update:
I think you should create your custom ViewPager with GestureDetector
Example:
public class ClickableViewPager extends ViewPager {
private OnItemClickListener mOnItemClickListener;
public ClickableViewPager(Context context) {
super(context);
setup();
}
public ClickableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
private void setup() {
final GestureDetector tapGestureDetector = new GestureDetector(getContext(), new TapGestureListener());
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(getCurrentItem());
}
return true;
}
}
}
and then in your activity
ClickableViewPager viewPager = (ClickableViewPager) findViewById(R.id.viewPager);
viewPager.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// HADNLE YOUR CLICKS
}
});
SOURCE

Related

get context after returning from adapter to fragment

I am using contextual action bar in my fragment("UnitsFragment.java") to delete and edit items of recyclerview. But when I come back from recyclerview adapter class("UnitsRv.java"). The context seems to be null. I tried returning context from adapter and it worked for function "prepareSelection". However for "onActionItemClicked" under ActionMode.callback, I need to get context so that I can use alertdialog for editing the items.
The "requireContext()" throws this error: Fragment UnitsFragment{e3a36c8 (b4957397-055a-4b1c-8af2-fee89a3e9b35)} not attached to a context.
Here are my codes.
UnitsFragment.java
public class UnitsFragment extends Fragment {
private static final String TAG = "UnitsFragment";
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<UnitsList> unitsLists = new ArrayList<>();
Activity mcontext = getActivity();
Context dcontext;
ActionMode actionMode;
public static ArrayList<UnitsList> selectionList = new ArrayList<>();
public static boolean isInActionMode = false;
List<String> list = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao().findUnitNameList();
public UnitsFragment() {
}
private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_item_action, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_edit:
if (selectionList.size() == 1) {
final EditText editText = new EditText(requireContext());
new AlertDialog.Builder(requireContext())
.setTitle("Rename unit name").setView(editText)
.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
UnitsList unitsList = selectionList.get(0);
unitsList.setUnit_name(editText.getText().toString().trim());
isInActionMode = false;
((UnitsRv) mAdapter).changeDataItem(getCheckedLastPosition(), unitsList);
actionMode.finish();
selectionList.clear();
}
})
.create()
.show();
Toast.makeText(getContext(), "Edit", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
}
case R.id.menu_item_delete:
isInActionMode = false;
((UnitsRv) mAdapter).removeData(selectionList);
Toast.makeText(getContext(), "Delete", Toast.LENGTH_SHORT).show();
actionMode.finish();
selectionList.clear();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
};
private int getCheckedLastPosition() {
ArrayList<UnitsList> dataSet = UnitsRv.getDataSet();
for (int i = 0; i < dataSet.size(); i++) {
if (dataSet.get(i).equals(selectionList.get(0))) {
return i;
}
}
return 0;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
dcontext = rootView.getContext();
Log.d(TAG, "onCreateView1: " + dcontext);
recyclerView = rootView.findViewById(R.id.rv_units);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.HORIZONTAL));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL));
layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
Log.d(TAG, "onCreateView: " + getContext());
mAdapter = new UnitsRv(mcontext,unitsLists);
recyclerView.setAdapter(mAdapter);
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.add, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new:
final View customLayout = getLayoutInflater().inflate(R.layout.add_unit_dialog, null);
final EditText edt_unit_name = customLayout.findViewById(R.id.edt_new_unit_name);
final AlertDialog dialog = new AlertDialog.Builder(getContext())
.setView(customLayout)
.setTitle("Unit name")
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button ok_btn = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button cancel_btn = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
ok_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String unit_name = edt_unit_name.getText().toString().trim();
if (!TextUtils.isEmpty(unit_name)) {
String old_unit_name = DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.findByUnitName(unit_name);
if (old_unit_name == null) {
DatabaseClient.getInstance(getContext())
.getUserDatabase()
.getUnitDao()
.insertUnits(new UnitsList(unit_name));
unitsLists.add(new UnitsList(unit_name));
dialog.dismiss();
} else {
edt_unit_name.setError("Unit already exists");
}
} else {
edt_unit_name.setError("Can't be empty");
}
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists);
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
private void updateViewCounter() {
int counter = selectionList.size();
if (counter == 1) {
actionMode.setTitle(counter + "item selected");
} else {
actionMode.setTitle(counter + "items selected");
}
}
}
This is my Adapter class.
UnitsRv.java
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment();
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists) {
mcontext = context;
munitsLists = unitsLists;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
unitsFragment.prepareSelection(mcontext,getAdapterPosition());
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
unitsFragment.prepareSelection(view.getContext(),getAdapterPosition());
return true;
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.units_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.unit_name.setText(munitsLists.get(position).getUnit_name());
if (UnitsFragment.isInActionMode){
if (UnitsFragment.selectionList.contains(munitsLists.get(position))){
holder.itemView.setBackgroundResource(R.color.colorSelected);
}
}
}
#Override
public int getItemCount() {
return munitsLists.size();
}
public static ArrayList<UnitsList> getDataSet() {
return munitsLists;
}
public void changeDataItem(int position, UnitsList unitsList) {
munitsLists.set(position, unitsList);
notifyDataSetChanged();
}
public void removeData(ArrayList<UnitsList> list) {
for (UnitsList unitsList : list) {
munitsLists.remove(unitsList);
}
notifyDataSetChanged();
}
}
First, you should not create instance of your UnitsFragment inside your adapter.
You can use EventBus to communicate between Activities, Fragments, Adapters, etc.
Or You can do your task using interface. like below.
Create an interface like this
public interface AdapterCallback {
void prepareSelection(Context context,int position);
}
In your UnitsFragment implement the above interface. like the following
public class UnitsFragment extends Fragment implements AdapterCallback{
// your other codes
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_units, container, false);
setHasOptionsMenu(true);
// .... your other codes
Log.d(TAG, "onCreateView: " + getContext());
// modify below line like this
mAdapter = new UnitsRv(mcontext, unitsLists, this); // here you have to pass an extra parameter that will implement your callback method from adapter.
recyclerView.setAdapter(mAdapter);
return rootView;
}
// ... you other codes
#Override
public void prepareSelection(Context context,int position) {
if(actionMode == null) {
isInActionMode = true;
for (String string : list) {
unitsLists.add(new UnitsList(string));
}
mAdapter = new UnitsRv(context, unitsLists,this); // add this as parameter.
Log.d(TAG, "prepareSelection: " + mAdapter);
Log.d(TAG, "prepareSelection1: " + dcontext);
mcontext = (Activity)context;
actionMode = mcontext.startActionMode(actionModeCallback);
mAdapter.notifyDataSetChanged();
if (!selectionList.contains(unitsLists.get(position))) {
selectionList.add(unitsLists.get(position));
}
updateViewCounter();
}
}
// other codes
}
Now, inside your Adapter you need to add an extra argument in constructor of UnitsRv and call your interface method from adapter ussing mAdapterCallback.
public class UnitsRv extends RecyclerView.Adapter<UnitsRv.ViewHolder> {
private static final String TAG = "UnitsRv";
private static ArrayList<UnitsList> munitsLists = new ArrayList<>();
UnitsFragment unitsFragment = new UnitsFragment(); // remove this line
private AdapterCallback mAdapterCallback; // add this line
Context mcontext;
public UnitsRv(Context context,ArrayList<UnitsList> unitsLists, AdapterCallback callback) {
mcontext = context;
munitsLists = unitsLists;
this.mAdapterCallback = callback; // add this line
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView unit_name;
public ViewHolder(View v) {
super(v);
unit_name = v.findViewById(R.id.unit_name);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
if (UnitsFragment.isInActionMode){
mAdapterCallback.prepareSelection(mcontext,getAdapterPosition()); // modify this line
notifyItemChanged(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
Log.d(TAG, "onLongClick: " + getAdapterPosition());
mAdapterCallback.prepareSelection(view.getContext(),getAdapterPosition()); // modify this line
return true;
}
}
// your other codes....
}
You should check for your fragment is attached or not with isAdded()
place if(!isAdded()) return in your onActionItemClicked. and replace requireContext() with getContext() because requireContext() always throws IllegalStateException if fragment is not attached.
override onAttach method to save context in your fragment.
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context= context;
}
Hope this helps.

How to display the Auto Scrolling RecyclerView position on TextView?

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.

Enable Button after list Item of RecyclerView was selected

I have an activity with a RecyclerView and a button that is disabled at first. The elements of the RV are selectable, and I want the button to be enabled only after an element was selected. I tried to set addOnItemTouchListener on the recyclerview, the problem is that it is also called when scrolling through the list.
Here is my Adapter:
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
private ArrayList<ClusterItem> mListOfClusters;
private OnItemClickListener mListener;
//index
int row_index = -1; //Default no row chosen
public interface OnItemClickListener{
//delete
void onDeleteCluster(int position);
//edit
void onEditCluster(int position);
//select
void onClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){mListener = listener;}
public static class ClusterListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mClusterName;
public TextView mClusterMembers;
public ImageView mDeleteCluster;
public ImageView mEditCluster;
//This
private OnItemClickListener itemClickListener;
public void setItemClickListener(OnItemClickListener listener){
this.itemClickListener = listener;
}
public ClusterListViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mClusterName = itemView.findViewById(R.id.tv_clusters_name_cluster_list);
mClusterMembers = itemView.findViewById(R.id.tv_clusters_members_cluster_list);
mDeleteCluster = itemView.findViewById(R.id.iv_delete_cluster);
mEditCluster = itemView.findViewById(R.id.iv_edit_cluster);
mDeleteCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onDeleteCluster(position);
}
}
}
});
mEditCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onEditCluster(position);
}
}
}
});
//used for highlighting item
itemView.setOnClickListener(this);
}
//This
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
public CLusterListAdapter(ArrayList<ClusterItem> listOfClusters ){ mListOfClusters = listOfClusters;}
#NonNull
#Override
public ClusterListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chose_your_cluster_list_item, viewGroup, false);
ClusterListViewHolder clusterListViewHolder = new ClusterListViewHolder(view, mListener);
return clusterListViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ClusterListViewHolder clusterListViewHolder, int i) {
ClusterItem currentCluster = mListOfClusters.get(i);
clusterListViewHolder.mClusterName.setText(currentCluster.getClustersName());
clusterListViewHolder.mClusterMembers.setText(currentCluster.getClustersMembers());
clusterListViewHolder.mClusterMembers.setSelected(true);
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
SpTAGs.selectedClusterPosition = position;
}
});
//Set highlight color
if(row_index == i) {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#E64A19"));
}else {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}
#Override
public int getItemCount() {
return mListOfClusters.size();
}
}
And here is how I applied the addOnItemTouch
clusterRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
selectButton.setEnabled(true);
Log.v("MyTAG", "Touch");
return false;
}
#Override
public void onTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
});
Any idea how to obtain this? Thank you!
Have a callback from the Adapter to the activity. Enable your button there.
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
...
interface Listener {
void onItemClick(int position);
}
}
Invoke this on item click
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
listener.onItemClick(position); // notify the listener (activity) of the click
SpTAGs.selectedClusterPosition = position;
}
});
In activity:
clusterRecyclerView.addOnItemTouchListener( ... );
clusterRecyclerView.setListener((int position) -> {
// logic to enable button goes here
});
you don't need to use the addOnItemTouchListener here.
just create a methode inside the activity like this
public void VisibleButton(){
yourButton.setVisibility(View.VISIBLE);
/**....*/
}
and just call the methode
VisibleButton()
from your adapter,from where you want your button to be visible, just like this
((YourActivityName)your_ACtivity_Context).VisibleButton();

Get data on click inside recycle view

I have build a list of data with a recyclerview. Everything works as expected. But I want to acces some data in my adapter when I click on a cell. The click works. But I don't know how to acces my events list.
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ViewHolder> {
private final LayoutInflater layoutInflater;
private final Context context;
private ArrayList<Event> events;
public ExampleAdapter(Context context, ArrayList<Event> events) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.events = events;
}
#Override
public ExampleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(layoutInflater.inflate(R.layout.activity_row, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.textView.setText(titles[position]);
holder.title.setText(events.get(position).getTitle());
holder.time.setText(events.get(position).getTime());
holder.places.setText(events.get(position).getPlacesLeft());
}
public void add(ArrayList<Event> events){
this.events = events;
this.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return events == null ? 0 : events.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView time;
TextView places;
ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.activity_title);
time = (TextView) view.findViewById(R.id.activity_time);
places = (TextView) view.findViewById(R.id.activity_places);
//textView = (TextView) view.findViewById(R.id.text_view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("ViewHolder", "onClick--> position = " + getPosition());
}
});
}
}
}
I have declared the onclick listener in the ViewHolder class. The click listener works as expected. But I want to acces the data in my events array. The only problem is that I can't acces it.
your onclick should be inside your onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.textView.setText(titles[position]);
holder.title.setText(events.getTitle());
holder.time.setText(events.getTime());
holder.places.setText(events.getPlacesLeft());
holder.yourview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//access from here
Toast.makeText(yourActivity.this,holder.yourview.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
If you just want to handle the click on the item you can do like this :
In your adapter write a function to get an event at a position :
public Event getEventAtPosition(int position) {
if (events != null && events.size() > position)
return events.get(position);
else return null;
}
Then implement a RecyclerTouchListener :
public interface ClickListener{
void onClick(View view,int position);
void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
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) {
}
}
Finally, you can use it this way :
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new ClickListener() {
#Override
public void onClick(View view, final int position) {
Event event= ((EventListAdapter)recyclerView.getAdapter()).getEventAtPosition(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
This way, you have only 1 ClickListener for all your recycler view, this is more optimal than declaring a listener for each item.
For more informations about RecyclerView and onClick, check this topic : RecyclerView onClick

unable to fetch images in image slider in fragment

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");
}
}
}

Categories

Resources