I am trying to pass view Id from Recyclerview Adapter to Activity,when the Recycler view List item is clicked.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter{
public interface OnRecyclerItemClickListener {
void onRecyclerItemClick(User data,int id);
}
List<User> dataSource;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private Context context;
public ActiveBeepsAdapter(List<User> dataArgs, OnRecyclerItemClickListener onRecyclerItemClickListener,Context context) {
this.dataSource = dataArgs;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_active_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view, onRecyclerItemClickListener);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
User user = dataSource.get(position);
holder.tvId.setText(user.getId());
Picasso.with(context)
.load(user.getProfilePicUrl())
.placeholder(R.drawable.bg_logo)
.error(R.drawable.bg_logo)
.transform(new CircleTransform())
.into(holder.ivUserProfile);
}
#Override
public int getItemCount() {
return dataSource.size();
}
#NonNull
#Override
public String getSectionName(int i) {
return String.valueOf(dataSource.get(i).getId().charAt(0));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
User data = new User();
TextView tvId;
ImageView ivUserProfile;
public ViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
tvId = (TextView)itemView.findViewById(R.id.tvName);
ivUserProfile = (ImageView)itemView.findViewById(R.id.ivProfilePic);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,id);
}
}
}
Suppose, If the Profile Image is clicked, the view id should sent to activity..
And My Activity
#EActivity
public class ActiveMessage extends AppCompatActivity implements Adapter.OnRecyclerItemClickListener{
#ViewById(R.id.toolbar)
Toolbar toolbar;
#ViewById(R.id.rvactiveMessage)
FastScrollRecyclerView rvmessage;
List<User> allUser;
#ViewById(R.id.toolbar_title)
TextView tv_toolbar;
#AfterViews
protected void init(){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_drop_down_black_24dp));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tv_toolbar.setText("Active Message");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
allUser = new ArrayList<>();
User user;
String fullName[] = {"ajay","kamal","akhil"};
String id[] = {"its_ajay","its_kamal","its_akhil"};
for(int i=0;i<id.length;i++){
user = new User();
user.setId(id[i]);
user.setFullName(fullName[i]);
allUser.add(user);
}
Adapter adapter = new Adapter(allUser,this,getApplicationContext());
rvmessage.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvmessage.setAdapter(activeBeepsAdapter);
}
#Override
public void onRecyclerItemClick(User data,int id) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (id == R.id.tvName){
Log.d("Id",data.getId());
}
}
public void noInternet(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.alert_dialog);
dialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_message);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
In my Activity, If the ProfileImage is clicked, pop up the dialog box.
Also, i need to check if there is Internet Connection when the list Item is clicked.
In adapter onClick method instead of id pass view:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,v);
}
Now in Activity
#Override
public void onRecyclerItemClick(User data,View view) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (view.getId() == R.id.tvName){
Log.d("Id",data.getId());
}
}
Related
Dialog with multiple buttons(cancalButton, deleteButton) is showed when click button in recyclerview item.
So I made two listener(cancelListener, deleteListener).
Show dialog is successful and cancelListener works well, But I can't do what I want in delteListener.
I wanna delete data in firebase when user click delete button in dialog.
So I have to know clicked recyclerview item's position to find data. (Because I can find data by getting key from array.get(position).getTimestamp.
How can I get item position in deleteListener?
public class AdapterExplorePlace extends RecyclerView.Adapter<AdapterExplorePlace.ViewHolder> implements Pin_BottomSheetDialog.BottomSheetListener {
ArrayList<ItemExplore> array;
Context context;
private AdapterExplorePlace.RecyclerViewClickListener listener;
private DialogDeletePin dialog;
DatabaseReference pinRef;
FirebaseAuth mAuth;
String currentPage;
#ColorInt int starColor;
#ColorInt int startextColor;
public AdapterExplorePlace(ArrayList<ItemExplore> array, Context context, AdapterExplorePlace.RecyclerViewClickListener listener) {
this.array = array;
this.context =context;
this.listener = listener;
}
#NonNull
#Override
public AdapterExplorePlace.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
SharedPreferences sharedPreferences = context.getSharedPreferences("file", MODE_PRIVATE);
starColor = sharedPreferences.getInt("starColor", 0);
startextColor = sharedPreferences.getInt("startextColor", 0);
currentPage = sharedPreferences.getString("currentPage", "");
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_explore_place,parent,false);
mAuth = FirebaseAuth.getInstance();
pinRef = FirebaseDatabase.getInstance().getReference("pinData").child(mAuth.getUid()).child(currentPage);
return new AdapterExplorePlace.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AdapterExplorePlace.ViewHolder holder, int position) {
if(array.get(position).getThumbnail() == null){
holder.explorePlaceImage.setImageResource(R.drawable.defalut_place_image);
}
else{
Glide.with(context)
.load(array.get(position).getThumbnail())
.centerCrop()
.dontAnimate()
.into(holder.explorePlaceImage);
}
holder.explorePlaceRegion.setText(String.valueOf(array.get(position).getPlaceAddress()));
holder.explorePlaceCategory.setText(String.valueOf(array.get(position).getPlaceCategory()));
holder.explorePlaceName.setText(String.valueOf(array.get(position).getPlaceName()));
holder.explorePlaceStyle.setText(String.valueOf(array.get(position).getPlaceStyle()));
holder.explorePlaceVisitedMember.setText(String.valueOf(array.get(position).getMember()));
holder.explorePlaceStyle.setTextColor(starColor);
holder.timestamp=String.valueOf(array.get(position).getTimestamp());
Drawable styleDrawable = ContextCompat.getDrawable(context,R.drawable.rounded);
styleDrawable.setColorFilter(new PorterDuffColorFilter(starColor, PorterDuff.Mode.SRC_IN));
holder.explorePlaceStyle.setBackground(styleDrawable);
pinRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot pinCheckSnap : snapshot.getChildren()){
Log.d("####Icon Check", String.valueOf(String.valueOf(pinCheckSnap.getValue()).contains(holder.timestamp)));
if(String.valueOf(pinCheckSnap.getValue()).contains(holder.timestamp)){
holder.btnExplorePlacePin.setBackgroundResource(R.drawable.ic_scrap_active);
holder.btnExplorePlacePin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(position);
}
});
break;
}
else {
holder.btnExplorePlacePin.setBackgroundResource(R.drawable.ic_scrap_inactive);
holder.btnExplorePlacePin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putString("timestamp", holder.timestamp);
Pin_BottomSheetDialog bottomSheet = new Pin_BottomSheetDialog();
bottomSheet .setArguments(args);
bottomSheet.show(((FragmentActivity)context).getSupportFragmentManager(), "pinBottomSheet");
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return array.size();
}
#Override
public void onButtonClicked(String text) {
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView explorePlaceImage;
TextView explorePlaceRegion;
TextView explorePlaceCategory;
TextView explorePlaceName;
TextView explorePlaceStyle;
TextView explorePlaceVisitedMember;
String timestamp;
ImageButton btnExplorePlacePin;
AdapterView.OnItemClickListener onItemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
explorePlaceImage =itemView.findViewById(R.id.explorePlaceImage);
explorePlaceRegion =itemView.findViewById(R.id.explorePlaceRegion);
explorePlaceCategory =itemView.findViewById(R.id.explorePlaceCategory);
explorePlaceName =itemView.findViewById(R.id.explorePlaceName);
explorePlaceStyle =itemView.findViewById(R.id.explorePlaceStyle);
explorePlaceVisitedMember =itemView.findViewById(R.id.explorePlaceVisitedMember);
btnExplorePlacePin =itemView.findViewById(R.id.btnExplorePlacePin);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.onClick(itemView, getAdapterPosition());
}
void setItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
}
private void openDialog(final int position){
dialog = new DialogDeletePin(context,cancelListener, deleteListener);
dialog.setCancelable(true);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
View.OnClickListener cancelListener = new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
};
View.OnClickListener deleteListener = new View.OnClickListener() {
public void onClick(View v) {
//I need to know item position for deleting data.
Log.d("####dialog","click delete");
dialog.dismiss();
}
};
}
DeleteDialogPin
class DialogDeletePin extends Dialog {
private Button btnCancelDeletePin;
private Button btnDeletePin;
private View.OnClickListener cancelListener;
private View.OnClickListener deleteListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 다이얼로그 외부 화면 흐리게 표현
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.6f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.dialog_delte_pin);
btnCancelDeletePin = findViewById(R.id.btnCancelDeletePin);
btnCancelDeletePin.setOnClickListener(cancelListener);
btnDeletePin = findViewById(R.id.btnDeletePin);
btnDeletePin.setOnClickListener(deleteListener);
//클릭이벤트
}
public DialogDeletePin(Context context, View.OnClickListener canceltListener, View.OnClickListener deleteListener) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
this.cancelListener = canceltListener;
this.deleteListener = deleteListener;
}
}
Since your method private void openDialog(final int position) has the position information. One of the way you can do it is just by creating a class for deleteListemer (DeleteListenerWithItemPos) and then pass the position as an argument at the constructor.
An example of how to implement is shown as follows:
private void openDialog(final int position){
deleteListener = new DeleteListenerWithItemPos(position);
dialog = new DialogDeletePin(context,cancelListener, deleteListener);
dialog.setCancelable(true);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
View.OnClickListener deleteListener;
public static class DeleteListenerWithItemPos implements View.OnClickListener() {
private int itemPos;
public DeleteListenerWithItemPos(int itemPos){
this.itemPos = itemPos;
}
public void onClick(View v) {=
itemPos; //get itemPos here
Log.d("####dialog","click delete");
dialog.dismiss();
}
}
public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}
Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.
Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});
I am working with recyclerview and sqlite database. i want to place a button in cardview such that whenever user clicks on that button, the respective record should be deleted from the table.
This is my adapter class for recyclerview
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private Context mContext;
private Cursor mCursor;
private butttonsAdapetrListener mlistener;
private RecyclerView.ViewHolder v;
public CardAdapter(Context context, Cursor cursor ,butttonsAdapetrListener listener){
mContext=context;
mCursor=cursor;
mlistener=listener;
}
#NonNull
#Override
public CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.mycard,parent,false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)){
return;
}
String name = mCursor.getString(mCursor.getColumnIndex("NAME"));
int total = mCursor.getInt(mCursor.getColumnIndex("TOTAL"));
int bunked = mCursor.getInt(mCursor.getColumnIndex("BUNK"));
int color = mCursor.getInt(mCursor.getColumnIndex("COLOR"));
long id= mCursor.getLong(mCursor.getColumnIndex("_id"));
holder.nameText.setText(name);
holder.totalText.setText(Integer.toString(total));
holder.bunkedText.setText(Integer.toString(bunked));
holder.colorText.setBackgroundColor(color);
holder.itemView.setTag(id);
v=holder;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public class CardViewHolder extends RecyclerView.ViewHolder{
public TextView nameText;
public TextView totalText;
public TextView bunkedText;
public TextView colorText;
public Button delete;
public CardViewHolder(#NonNull View itemView) {
super(itemView);
nameText= itemView.findViewById(R.id.name);
totalText = itemView.findViewById(R.id.total_num);
bunkedText = itemView.findViewById(R.id.bunked_num);
colorText= itemView.findViewById(R.id.color);
delete= itemView.findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mlistener.deleteOnClick(v,getAdapterPosition());
}
});
}
}
public interface butttonsAdapetrListener{
void deleteOnClick(RecyclerView.ViewHolder v,long position);
}
public void swapCursor(Cursor newCursor){
if(mCursor!=null){
mCursor.close();
}
mCursor=newCursor;
if(newCursor!=null){
notifyDataSetChanged();
}
}
}
This is my main activity code to delete record from database
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase db;
private CardAdapter mAdapter;
private long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteOpenHelper proBunkerDatabaseHelper = new ProBunkerDatabaseHelper(this);
db = proBunkerDatabaseHelper.getWritableDatabase();
RecyclerView recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(RecyclerView.ViewHolder v, long position) {
id = (long)v.itemView.getTag();
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
recyclerView.setAdapter(mAdapter);
FloatingActionButton b = findViewById(R.id.fab);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddSubject.class);
startActivity(intent);
}
});
}
public Cursor getCursor(){
return db.query("MYTABLE",null,null,null,null,null,"_id ASC");
}
}
The main problem is the when I click on the delete button in any item it is deleting the item which is last in the cursor.
there are no compilation errors and runtime issues only the records are not deleting in correct order.
Try it like this:
Your interface:
public interface butttonsAdapetrListener{
void deleteOnClick(int id,long adapterPos);
}
Inside your CardViewHolder:
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = (int)view.getTag();
mlistener.deleteOnClick(id,getAdapterPosition());
}
});
In onBindViewHolder
holder.delete.setTag(id);
In MainActivity onCreate
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(int id, long position) {
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
Another alternative
If you want your activity to be clean and not handle data from within.
Keep it for the adapter to handle the data being deleted and notifying any change.
Just create a listener for the button in the onbindviewholder method.
I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}
I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);