Well, at the beginning of the Implementation of ItemTouchHelper, I chose to use only the Swipe function from it. Everything worked - with the help of Swipe I could delete items in RecyclerView etc. But then I thought I'd add up-down movement so that the user could change the order in which the item appears in the list.
Then the problems began - the user can change the order in which items are displayed, but can no longer:
Scroll RecyclerView (even if changing item up-down position is disabled)
Swipe functions have stopped working - onSwiped does not return the side (ItemTouchHelper.LEFT, ItemTouchHelper.RIGHT) in which the item was swiped
I changed the View on which is trigger OnStartDragListener from _view to just ImageView and I can scroll now but there are now other problems:
Swipe works on that ImageView too - I want to be able to swipe item whereever user click on item (_view)
Swipe functions still doesn't work - onSwiped does not return the side (ItemTouchHelper.LEFT, ItemTouchHelper.RIGHT) in which the item was swiped
Video how the problem looks
FIXED
I Changed
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags =
mDraggable
? ItemTouchHelper.UP
| ItemTouchHelper.DOWN
| ItemTouchHelper.START
| ItemTouchHelper.END
: 0;
if (mDraggable) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
} else {
dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
}
return makeMovementFlags(dragFlags, 0);
}
To
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = 0;
int swipeFlags = 0;
if (mDraggable) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
return makeMovementFlags(dragFlags, 0);
} else {
swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(0, swipeFlags);
}
}
RecyclerView Adapter:
package tw.codeassist.plus;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import tw.codeassist.plus.SwipeToDeleteCallback;
public class CodeAdapter extends RecyclerView.Adapter<CodeAdapter.ViewHolder> implements SwipeToDeleteCallback.ItemTouchHelperAdapter {
ArrayList<HashMap<String, Object>> _data;
Context context;
SharedPreferences snippets;
OnItemClickListener mItemClickListener;
private static final int TYPE_ITEM = 0;
//private final LayoutInflater mInflater;
private final tw.codeassist.plus.SwipeToDeleteCallback.OnStartDragListener mDragStartListener;
public CodeAdapter(
android.content.Context appCont,
ArrayList<HashMap<String, Object>> _arr,
tw.codeassist.plus.SwipeToDeleteCallback.OnStartDragListener dragListner) {
_data = _arr;
context = appCont;
mDragStartListener = dragListner;
snippets = context.getSharedPreferences("snippets", Activity.MODE_PRIVATE);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater _inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View _v = _inflater.inflate(R.layout.codesnippets, null);
RecyclerView.LayoutParams _lp =
new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
_v.setLayoutParams(_lp);
return new ViewHolder(_v);
}
#Override
public void onBindViewHolder(ViewHolder _holder, final int _position) {
View _view = _holder.itemView;
final androidx.cardview.widget.CardView cardview1 = _view.findViewById(R.id.cardview1);
final LinearLayout main_linear = (LinearLayout) _view.findViewById(R.id.main_linear);
final LinearLayout color_linear = (LinearLayout) _view.findViewById(R.id.color_linear);
final LinearLayout linear3 = (LinearLayout) _view.findViewById(R.id.linear3);
final TextView title_txt = (TextView) _view.findViewById(R.id.title_txt);
final TextView desc_txt = (TextView) _view.findViewById(R.id.desc_txt);
title_txt.setTypeface(
Typeface.createFromAsset(context.getAssets(), "fonts/product_sans_bold.ttf"), 0);
desc_txt.setTypeface(
Typeface.createFromAsset(context.getAssets(), "fonts/product_sans_regular.ttf"), 0);
title_txt.setText(_data.get((int) _position).get("Title").toString());
desc_txt.setText(_data.get((int) _position).get("Description").toString());
color_linear.setBackgroundColor(
Color.parseColor(_data.get((int) _position).get("Color").toString()));
RecyclerView.LayoutParams _lp =
new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
_view.setLayoutParams(_lp);
_view.setOnTouchListener(
new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mDragStartListener.onStartDrag(_holder);
}
return false;
}
});
}
#Override
public int getItemCount() {
return _data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, ItemTouchHelperViewHolder {
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getAdapterPosition());
}
}
#Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
#Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
#Override
public void onItemDismiss(int position) {
_data.remove(position);
notifyItemRemoved(position);
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Log.d("onItemMove", "Log position" + fromPosition + " " + toPosition);
if (fromPosition < _data.size() && toPosition < _data.size()) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(_data, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(_data, i, i - 1);
}
}
Collections.reverse(_data);
snippets.edit().putString("CodeSnippets", new Gson().toJson(this._data)).commit();
notifyItemMoved(fromPosition, toPosition);
}
return true;
}
public void showMessage(String message) {
Toast.makeText((Activity) context, message, Toast.LENGTH_SHORT).show();
}
public void updateList(ArrayList<HashMap<String, Object>> list) {
_data = list;
notifyDataSetChanged();
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public void removeAt(int position) {
_data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, _data.size());
}
public interface ItemTouchHelperViewHolder {
void onItemSelected();
void onItemClear();
}
}
ItemTouchHelper Callback
package tw.codeassist.plus;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
public class SwipeToDeleteCallback extends ItemTouchHelper.Callback {
private CodeAdapter mAdapter;
Context context;
private SharedPreferences snippets;
private Drawable icon;
private Drawable icon2;
private GradientDrawable background; // ColorDrawable Before
boolean mDraggable = true;
public SwipeToDeleteCallback(Context con, CodeAdapter adapter, boolean canEdit) {
mAdapter = adapter;
context = con;
setDraggable(canEdit);
DisplayMetrics dm = new DisplayMetrics();
((Activity) con).getWindowManager().getDefaultDisplay().getMetrics(dm);
float densityScale = dm.density;
// DELETE ICON
Drawable dr = con.getResources().getDrawable(R.drawable.ic_delete);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
icon =
new BitmapDrawable(
con.getResources(),
Bitmap.createScaledBitmap(
bitmap,
(int) (150 * densityScale / 3),
(int) (150 * densityScale / 3),
true));
// COPY ICON
Drawable dr2 = con.getResources().getDrawable(R.drawable.ic_copy);
Bitmap bitmap2 = ((BitmapDrawable) dr2).getBitmap();
icon2 =
new BitmapDrawable(
con.getResources(),
Bitmap.createScaledBitmap(
bitmap2,
(int) (200 * densityScale / 3),
(int) (200 * densityScale / 3),
true));
// TO INIT THE background
int startColor = Color.WHITE;
int endColor = Color.RED;
background =
new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, new int[] {startColor, endColor});
background.setCornerRadius(20);
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags =
mDraggable
? ItemTouchHelper.UP
| ItemTouchHelper.DOWN
| ItemTouchHelper.START
| ItemTouchHelper.END
: 0;
if (mDraggable) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
} else {
dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
}
return makeMovementFlags(dragFlags, 0);
}
public void setDraggable(boolean value) {
mDraggable = value;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean onMove(
RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
if (mDraggable) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
} else {
return false;
}
}
void showMessage(String message) {
Toast.makeText(((Activity) context), message, Toast.LENGTH_SHORT).show();
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
showMessage(String.valueOf(direction));
if (direction == 8) { // RIGHT TO LEFT
// copy
VibrateNotify(200);
String getCode = mAdapter._data.get((int) position).get("Code").toString();
CharSequence code = getCode;
LinearLayout linearSnack =
(LinearLayout) ((FragmentActivity) context).findViewById(R.id.linear1);
((ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE))
.setPrimaryClip(ClipData.newPlainText("", code));
com.google.android.material.snackbar.Snackbar.make(
context,
linearSnack,
"Code Copied!",
com.google.android.material.snackbar.Snackbar.LENGTH_LONG)
.setAction(
"",
new View.OnClickListener() {
#Override
public void onClick(View _view) {}
})
.show();
mAdapter.notifyItemChanged(position);
} else if (direction == 4) { // 4 = LEFT TO RIGHT
// delete
mAdapter.removeAt(position);
VibrateNotify(500);
snippets = context.getSharedPreferences("snippets", context.MODE_PRIVATE);
snippets.edit().putString("CodeSnippets", new Gson().toJson(mAdapter._data)).commit();
mAdapter.notifyItemRemoved(position);
}
}
public void VibrateNotify(long duration) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.EFFECT_DOUBLE_CLICK));
} else {
// deprecated in API 26
v.vibrate(duration);
}
}
#Override
public void onChildDraw(
Canvas c,
RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder,
float dX,
float dY,
int actionState,
boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
View itemView = viewHolder.itemView;
int backgroundCornerOffset = 15; // so background is behind the rounded corners of itemView
int alpha = 128;
int colorGreen = Color.parseColor("#FF0000FF");
icon.setAlpha(alpha);
icon2.setAlpha(alpha);
int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 3;
int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconBottom = iconTop + icon.getIntrinsicHeight();
if (dX > 0) { // Swiping to the right
int iconLeft = itemView.getLeft() + iconMargin; // icon.getIntrinsicWidth()
int iconRight = iconLeft + icon.getIntrinsicWidth(); // itemView.getLeft()
icon2.setBounds(iconLeft, iconTop, iconRight, iconBottom);
int START = 0xFF90A4AE;
int END = Color.TRANSPARENT;
background =
new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, new int[] {START, END});
background.setCornerRadius(20);
background.setBounds(
itemView.getLeft(),
itemView.getTop(),
itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
itemView.getBottom());
} else if (dX < 0) { // Swiping to the left
int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
int iconRight = itemView.getRight() - iconMargin;
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
int START = Color.TRANSPARENT;
int END = 0xFFE57373;
background =
new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, new int[] {START, END});
background.setCornerRadius(20);
background.setBounds(
itemView.getRight() + ((int) dX) - backgroundCornerOffset,
itemView.getTop(),
itemView.getRight(),
itemView.getBottom());
} else { // view is unSwiped
icon.setBounds(0, 0, 0, 0);
icon2.setBounds(0, 0, 0, 0);
background.setBounds(0, 0, 0, 0);
}
background.setStroke(25, Color.TRANSPARENT);
// background.setPadding(0, paddingTop, 0, paddingBottom); //left, top, right, bottom
background.draw(c);
icon.draw(c);
icon2.draw(c);
}
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}
}
Fragment where the RecyclerView is:
package tw.codeassist.plus;
import android.animation.*;
import android.app.*;
import android.app.Activity;
import android.content.*;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.*;
import android.graphics.*;
import android.graphics.Typeface;
import android.graphics.drawable.*;
import android.media.*;
import android.net.*;
import android.os.*;
import android.text.*;
import android.text.style.*;
import android.util.*;
import android.view.*;
import android.view.View;
import android.view.View.*;
import android.view.animation.*;
import android.webkit.*;
import android.widget.*;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.*;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.*;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.github.angads25.filepicker.*;
import com.github.dhaval2404.colorpicker.*;
import com.google.android.flexbox.*;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zip4j.*;
import io.github.rosemoe.sora.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.*;
import org.json.*;
public class TutorialsFragmentActivity extends Fragment
implements SwipeToDeleteCallback.OnStartDragListener {
private FloatingActionButton _fab;
private CodeAdapter codeAdapter;
private ArrayList<HashMap<String, Object>> dataToShow = new ArrayList<>();
public LinearLayout linear1;
private TextView textview1;
private TextView goneTxt;
private TextView editBttn;
private RecyclerView recyclerView;
private LinearLayout noCodesView;
TutorialsFragmentActivity tfa = this;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
private Intent intent = new Intent();
private SharedPreferences snippets;
private SharedPreferences settings;
private ItemTouchHelper itemTouchHelper;
boolean isEditMode = false;
#NonNull
#Override
public View onCreateView(
#NonNull LayoutInflater _inflater,
#Nullable ViewGroup _container,
#Nullable Bundle _savedInstanceState) {
View _view = _inflater.inflate(R.layout.tutorials_fragment, _container, false);
initialize(_savedInstanceState, _view);
com.google.firebase.FirebaseApp.initializeApp(getContext());
initializeLogic();
return _view;
}
private void initialize(Bundle _savedInstanceState, View _view) {
_fab = _view.findViewById(R.id._fab);
settings = getContext().getSharedPreferences("settings", Activity.MODE_PRIVATE);
noCodesView = _view.findViewById(R.id.linearNoCodes);
linear1 = _view.findViewById(R.id.linear1);
goneTxt = _view.findViewById(R.id.txGone);
editBttn = _view.findViewById(R.id.edit);
textview1 = _view.findViewById(R.id.textview1);
recyclerView = _view.findViewById(R.id.recyclerView);
snippets = getContext().getSharedPreferences("snippets", Activity.MODE_PRIVATE);
listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("CodeSnippets")) {
if (settings.getString("ShouldRefresh", "") == "true") {
itemTouchHelper.attachToRecyclerView(null);
dataToShow =
new Gson()
.fromJson(
snippets.getString("CodeSnippets", ""),
new TypeToken<
ArrayList<
HashMap<
String,
Object>>>() {}.getType());
Collections.reverse(dataToShow);
codeAdapter = new CodeAdapter(getContext(), dataToShow, tfa);
recyclerView.setAdapter(codeAdapter);
//recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
itemTouchHelper =
new ItemTouchHelper(
new SwipeToDeleteCallback(
getContext(), codeAdapter, false));
itemTouchHelper.attachToRecyclerView(recyclerView);
settings.edit().putString("ShouldRefresh", "false").commit();
} else {
}
}
}
};
snippets.registerOnSharedPreferenceChangeListener(listener);
goneTxt.setVisibility(View.INVISIBLE);
editBttn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View _view) {
if (!isEditMode) {
isEditMode = true;
editBttn.setText("Close");
goneTxt.setText("Close");
} else {
isEditMode = false;
editBttn.setText("Edit");
goneTxt.setText("Edit");
}
itemTouchHelper.attachToRecyclerView(null);
itemTouchHelper =
new ItemTouchHelper(
new SwipeToDeleteCallback(
getContext(), codeAdapter, isEditMode));
itemTouchHelper.attachToRecyclerView(recyclerView);
}
});
_fab.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View _view) {
editBttn.setText("Edit");
goneTxt.setText("Edit");
isEditMode = false;
itemTouchHelper.attachToRecyclerView(null);
itemTouchHelper =
new ItemTouchHelper(
new SwipeToDeleteCallback(
getContext(), codeAdapter, isEditMode));
itemTouchHelper.attachToRecyclerView(recyclerView);
intent.setClass(
getContext().getApplicationContext(), AddSnippetActivity.class);
startActivity(intent);
}
});
}
#Override
public void onResume() {
}
#Override
public void onStart() {
super.onStart();
}
public void onPause() {
super.onPause();
}
private void initializeLogic() {
{
android.graphics.drawable.GradientDrawable SketchUi =
new android.graphics.drawable.GradientDrawable();
int clrs[] = {0xFFFFFFFF, 0xFFE0E0E0};
SketchUi =
new android.graphics.drawable.GradientDrawable(
android.graphics.drawable.GradientDrawable.Orientation.TOP_BOTTOM,
clrs);
linear1.setBackground(SketchUi);
}
noCodesView.setVisibility(View.GONE);
textview1.setTypeface(
Typeface.createFromAsset(getContext().getAssets(), "fonts/product_sans_bold.ttf"),
0);
dataToShow =
new Gson()
.fromJson(
snippets.getString("CodeSnippets", ""),
new TypeToken<ArrayList<HashMap<String, Object>>>() {}.getType());
Collections.reverse(dataToShow);
codeAdapter = new CodeAdapter(this.getContext(), dataToShow, this);
recyclerView.setAdapter(codeAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
itemTouchHelper =
new ItemTouchHelper(new SwipeToDeleteCallback(getContext(), codeAdapter, false));
itemTouchHelper.attachToRecyclerView(recyclerView);
removeScrollBar(recyclerView);
if (dataToShow.size() == 0) {
noCodesView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
noCodesView.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void removeScrollBar(View _view) {
_view.setVerticalScrollBarEnabled(false);
_view.setHorizontalScrollBarEnabled(false);
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
itemTouchHelper.startDrag(viewHolder);
}
}
FIXED
I Changed
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags =
mDraggable
? ItemTouchHelper.UP
| ItemTouchHelper.DOWN
| ItemTouchHelper.START
| ItemTouchHelper.END
: 0;
if (mDraggable) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
} else {
dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
}
return makeMovementFlags(dragFlags, 0);
}
To
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = 0;
int swipeFlags = 0;
if (mDraggable) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
return makeMovementFlags(dragFlags, 0);
} else {
swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(0, swipeFlags);
}
}
My code was worked perfectly just before i added header image, after that listview not showing the given datas.
These are the main pages.
Can anyone help please.Any help will be appreciated.
MyRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyRecyclerViewAdapter extends
RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
Context context;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public MyRecyclerViewAdapter(String[] data) {
this.data = data;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView desc;
ImageView image,head_img;
public DataObjectHolder(View itemView) {
super(itemView);
desc = (TextView) itemView.findViewById(R.id.description);
image = (ImageView) itemView.findViewById(R.id.image);
head_img=(ImageView) itemView.findViewById(R.id.header_img);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
this.context=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType==TYPE_ITEM) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
else if (viewType==TYPE_HEADER){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
if(holder instanceof VHItem) {
holder.desc.setText(mDataset.get(position ).getDescription());
// holder.image.setText(mDataset.get(position).getImage_url());
Picasso.with(holder.image.getContext()).load(mDataset.get(position ).getImage_url()).into(holder.image);
}
else if(holder instanceof VHHeader){
holder.head_img.setImageResource(R.drawable.cam);
}
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return (null != mDataset ? mDataset.size() + 1 : 0);
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private class VHItem extends DataObjectHolder {
public VHItem(View itemView) {
super(itemView);
}
}
private class VHHeader extends DataObjectHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
}
Profile2Fragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Profile2Fragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
return rootview;
}
private ArrayList<DataObject> getDataSet() {
ArrayList<DataObject> results = new ArrayList<DataObject>();
for (int index = 0; index < 1; index++) {
DataObject obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://mediastream.jumeirah.com/webimage/heroactual//globalassets/global/hotels-and-resorts/dubai/madinat-jumeirah/restaurants/pierchic/madinat-jumeirah-pierchic-inside-restaurant-02-hero.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://photos.smugmug.com/Portfolio/i-HBk894k/0/db7f0344/L/The%20Black%20Couches-L.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "http://thesmartlocal.com/images/easyblog_images/82/Pollen.jpg");
results.add(obj);
}
return results;
}
}
DataObject.java
public class DataObject {
private String description;
private String image_url;
DataObject (String text1, String text2){
description = text1;
image_url = text2;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
try to change return statement
`return new DataObjectHolder(view);
to your specific Class like return
new VHHeader(view);
and
return new VHItem(view);
in onCreateViewHolder..
/**
* Created by Prateek on 2/18/2017.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import newsee.novasyslabs.com.nodefetch.Others.CircularTransform;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
Context mContext;
public static ArrayList <String> embed_html = new ArrayList<>();
public static ArrayList <String> channel_thumbnail = new ArrayList<>();
public static ArrayList <String> channel_title = new ArrayList<>();
public static ArrayList <String> video_title = new ArrayList<>();
public static ArrayList <String> created_time = new ArrayList<>();
public static ArrayList <Integer> android_likes = new ArrayList<>();
public static ArrayList <Integer> pf_likes = new ArrayList<>();
public static ArrayList <Integer> android_views = new ArrayList<>();
public static ArrayList <Integer> pf_views = new ArrayList<>();
public RecyclerAdapter(Context mContext){
this.mContext = mContext;
}
class ViewHolder extends RecyclerView.ViewHolder{
WebView webView;
public ImageView chlogo;
public TextView chtitle;
public TextView vidtitle;
public TextView upld_time;
public TextView show_views;
public TextView show_likes;
public ImageView mLike;
int j = 0;
public ViewHolder(View itemView) {
super(itemView);
this.mLike = (ImageView)itemView.findViewById(R.id.video_like);
this.show_views = (TextView) itemView.findViewById(R.id.video_views_count);
this.show_likes = (TextView) itemView.findViewById(R.id.likes_count);
this.webView = (WebView) itemView.findViewById(R.id.web);
this.chlogo = (ImageView) itemView.findViewById(R.id.ch_logo);
this.chtitle = (TextView) itemView.findViewById(R.id.ch_name);
this.vidtitle = (TextView) itemView.findViewById(R.id.video_title);
this.upld_time = (TextView)itemView.findViewById(R.id.ch_time);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_card, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.j==0) {
holder.mLike.setImageResource(R.drawable.liked);
CharSequence like = holder.show_likes.getText();
int new_like = Integer.parseInt((String) like) + 1;
Toast.makeText(mContext,"Liked" +new_like ,Toast.LENGTH_SHORT).show();
holder.j = 1;
} else {
holder.mLike.setImageResource(R.drawable.unlike);
CharSequence like = holder.show_likes.getText();
int new_like = Integer.parseInt((String) like) - 1;
Toast.makeText(mContext,"Unliked" +new_like,Toast.LENGTH_SHORT).show();
holder.j = 0;
}
}
});
holder.webView.getSettings().setJavaScriptEnabled(true);
holder.webView.loadData(embed_html.get(position), "text/html", "utf-8");
Picasso.with(mContext).load(channel_thumbnail.get(position)).transform(new CircularTransform()).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(holder.chlogo);
holder.chtitle.setText(channel_title.get(position));
holder.vidtitle.setText(video_title.get(position));
holder.upld_time.setText(created_time.get(position));
int and_views = android_views.get(position);
int views = pf_views.get(position);
views += and_views;
int and_likes = android_likes.get(position);
int likes = pf_likes.get(position);
likes += and_likes;
holder.show_views.setText("" + views);
holder.show_likes.setText("" + likes);
}
#Override
public int getItemCount() {
return embed_html.size();
}
}
when i am clicking then image change for 0th postion then 4,8,12.... why onclicklistener effect every 4 object in recyclerview i am changing the image resource onClick but the images changes for 4postion, 8position
I would recommend doing it this way, first in your onBindViewHolder method add this code:
holder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImage(position);
}
}
});
Then create a new method in this class only:
public void showImage(int position){
if (position == 0) {
holder.imageView.setImageResource(R.drawable.medal);
}
...
}
I would like to stop listview after loading from server instead of moving up when I scrolldown veryfast.
I tired setFriction property also but it doesn't seem to be that much effective.
Can anybody suggest how to control this?
This is my code.
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
View footerView;
ProgressDialog progress;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
dataArrayList = new ArrayList<DataObject>();
footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
if (isOnline(_activity)) {
progress = new ProgressDialog(this);
lv.setFriction(ViewConfiguration.getScrollFriction() * 0.5f);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
// ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (dataArrayList.size() == 0) {
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
loadingMore = true;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progress.dismiss();
try {
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
// dataListAdapter.add(dataObject);
}
lv.addFooterView(footerView);
dataListAdapter.notifyDataSetChanged();
loadingMore = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}
I am a beginner programmer so please bear with me. I have been able to create a listview with images in it and thought I could modify it to add a checkbox. However, this setup does not work. Any suggestions to how I may fix my code to create a listview with both an image and checkbox?
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CheckboxList extends ListActivity{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static CheckBox box0,box1,box2,box3;
static final String[] title = new String[] {
"Box 1", "Box 2",
"Box 3 ","Box 4" };
static final CheckBox[] boxes= new CheckBox[] {box0,box1,box2,box3};
private Integer[] imgid = {
R.drawable.magnum,R.drawable.mg,R.drawable.mk,
R.drawable.mk46};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],boxes[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.check_list,
R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class RowData {
protected int mId;
protected String mTitle;
protected CheckBox mCBox;
RowData(int id,String title,CheckBox cbox){
mId=id;
mTitle = title;
mCBox=cbox;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mCBox;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
CheckBox box = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.check_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
box = holder.getcheckbox();
box.setChecked(false);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private CheckBox cbox = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public CheckBox getcheckbox() {
if(null == cbox){
cbox = (CheckBox) mRow.findViewById(R.id.checkBox);
}
return cbox;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
} }
Look at this links.it may helpfull......
http://www.vogella.com/articles/AndroidListView/article.html
CustomListview With Images and Checkboxes Example