I'm trying to make a transition between my RecyclewView and a activity when onClick, but the Adapter doesn't let it. Any suggestion in how could I solve this problem?
My onBindViewHolder that contains the target onClick method which I want to implement the transition animation:
public void onBindViewHolder(#NonNull DataRVAdapter.ViewHolder holder, int position) {
// setting data to our views in Recycler view items.
DataModal modal = dataModalArrayList.get(position);
holder.bookName.setText(modal.getName());
// we are using Picasso to load images
// from URL inside our image view.
Picasso.get().load(modal.getCover()).placeholder(R.drawable.book_placeholder).into(holder.bookCover);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setting on click listener
// for our items of recycler items.
//Toast.makeText(context, "Clicked item is " + modal.getName(), Toast.LENGTH_SHORT).show();
// open activity with our book information
Intent intent = new Intent(holder.itemView.getContext(), BookDetailsActivity.class);
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(holder.itemView.getContext(),holder.bookCover, ViewCompat.getTransitionName(holder.bookCover));
intent.putExtra("name", dataModalArrayList.get(position).getName());
intent.putExtra("cover", dataModalArrayList.get(position).getCover());
intent.putExtra("author", dataModalArrayList.get(position).getAuthor());
intent.putExtra("date", dataModalArrayList.get(position).getDate());
intent.putExtra("publisher", dataModalArrayList.get(position).getPublisher());
intent.putExtra("pages", dataModalArrayList.get(position).getPages());
intent.putExtra("genre", dataModalArrayList.get(position).getGenre());
intent.putExtra("isbn", dataModalArrayList.get(position).getIsbn());
intent.putExtra("synopsis", dataModalArrayList.get(position).getSynopsis());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
holder.itemView.getContext().startActivity(intent, optionsCompat.toBundle());
}
});
}
And here's my ViewHolder:
// creating variables for our
// views of recycler items.
private TextView bookName;
private ImageView bookCover;
public ViewHolder(#NonNull View itemView) {
super(itemView);
// initializing the views of recycler views.
bookName = itemView.findViewById(R.id.idTVtext);
bookCover = itemView.findViewById(R.id.idIVimage);
}
}
These codes are all inside my RecyclewView Adapter
So thank you in advance!
Related
I am new to android programming. I am unable to find startActivityForResult(intent) within onBindViewHolder in the recycler adapter.
I have a recycler view adapter containing some items for MainActivity(1). This Activity 1 contains some elements which are hidden. If the user clicks on any item, he/she is taken to a new activity(2). Activity2 contains a button, which when clicked, changes the items in Activity 1 to be visible.
On doing some research, I found that I need to use startActivityForResult instead of startActivity if I am expecting results back from Activity2. But I am unable to find startActivityForResult(intent) within onBindViewHolder in the recycler adapter for Activity1.
Am I doing something wrong? Below is the recycler view code
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.txtItem.setText(items.get(position).getItemName());
holder.txtShortDesc.setText(items.get(position).getItemShortDesc());
holder.txtShortDesc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, LongDesc.class);
intent.putExtra(ITEM_ID_KEY, items.get(position).getId());
startActivityForResult(intent);
I'm trying to design a page where address are stored in recycler view -> cardview.
When the user clicks the add address button from the Activity A the user is navigated to the add address page in Activity B. Here the user can input customer name, address line 1 and address line two.
And once save button is clicked in Activity B, a cardview should be created under the add address button in the Activity A.
This design is just like the amazon mobile app add address option.
Could anyone give me an example hoe to pass the saved data from activity to recycler adapter. I know how to pass data from recycler adapter to activity with putExtra etc..
Kindly help me. Million Thanks in advance!
Code In Activity A(Where the Add address button is available and where the recycler view is present)
public class ProfileManageAdressFragment extends AppCompatActivity {
RecyclerView recyclerView;
ProfileManageAddressRecyclerAdapter adapter;
ArrayList<ProfileManageAddressGetterSetter> reviews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_profile_manage_adress);
Button addAddress = findViewById(R.id.addNewAddress);
reviews = new ArrayList<>();
addAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProfileManageAdressFragment.this, AddNewAddress.class);
startActivity(intent);
}
});
}
}
Piece of Code that is responsible for adding a card view in Activity A. Kindly let me know how to invoke this below code on button click in Activity
reviews.add(new ProfileManageAddressGetterSetter("Customer Name", "address line 1", "address line 2"));
recyclerView = findViewById(R.id.addressRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(ProfileManageAdressFragment.this));
adapter = new ProfileManageAddressRecyclerAdapter(this, reviews);
recyclerView.setAdapter(adapter);
Code in the Recycler adapter
public class ProfileManageAddressRecyclerAdapter extends RecyclerView.Adapter<ProfileManageAddressRecyclerAdapter.ViewHolder> {
private ArrayList<ProfileManageAddressGetterSetter> mDataset = new ArrayList<>();
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView customer_name, address_one, address_two;
private Button edit, remove;
public ViewHolder(View v) {
super(v);
customer_name = (TextView) v.findViewById(R.id.customerName);
address_one = (TextView) v.findViewById(R.id.addressLineOne);
address_two = v.findViewById(R.id.addressLineTwo);
}
}
public ProfileManageAddressRecyclerAdapter(View.OnClickListener profileManageAdressFragment, ArrayList<ProfileManageAddressGetterSetter> dataset) {
mDataset.clear();
mDataset.addAll(dataset);
}
#Override
public ProfileManageAddressRecyclerAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_manage_address, parent, false);
ProfileManageAddressRecyclerAdapter.ViewHolder vh = new ProfileManageAddressRecyclerAdapter.ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ProfileManageAddressRecyclerAdapter.ViewHolder holder, int position) {
ProfileManageAddressGetterSetter profileManageAddressGetterSetter = mDataset.get(position);
holder.address_one.setText(profileManageAddressGetterSetter.getAddress_line_1());
holder.address_two.setText(profileManageAddressGetterSetter.getGetAddress_line_2());
holder.customer_name.setText(profileManageAddressGetterSetter.getContractor_name());
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
enter image description here - After trying the call from adapter using intent as mentioned above ended up with a 0.
Code in the Activity B
public class AddNewAddress extends AppCompatActivity {
private EditText customer_name, address_one, address_two;
private TextView cancel;
private Button add_address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_address);
customer_name = findViewById(R.id.customerName);
address_one = findViewById(R.id.addressOne);
address_two = findViewById(R.id.addressTwo);
add_address = findViewById(R.id.addAddress);
cancel = findViewById(R.id.completeCancel);
String cancel_text = "Cancel";
SpannableString spanableObject = new SpannableString(cancel_text);
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(AddNewAddress.this, "Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
}
};
spanableObject.setSpan(clickableSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
cancel.setText(spanableObject);
cancel.setMovementMethod(LinkMovementMethod.getInstance());
final ProfileManageAdressFragment profileManageAdressFragment = new ProfileManageAdressFragment();
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddNewAddress.this, ProfileManageAdressFragment.class);
startActivity(intent);
}
});
}
private void setFragment(android.support.v4.app.Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment).commit();
}
}
Update 1:
Kindly check my updated Recycler adapter. When I run this 0 is displayed in the text area as shown in the attached image. I'm new to android. Kindly help with example.
I finally achieved my goal with the use of ActivityResult. Now I'm able to pass data from Activity to Cardview.
Solution: When button is clicked in Activity A, I start the activity with startResultActivity(). Later, when the Activity B i triggered. The end-user inputs the data and that data is passed with the use of putExtra() and once the save button is clicked in Activity B next setResult() in Activity B and finish().
Finally i define onActivityResult() in Activity A to get the result. Works well!!
I would create a global variable and then store all the data in that variable and simply just call that variable in adapter.
declare a global variable and assign null value to it:
public static String checking = null;
a then store data in when you need it:
checking = check.getText().toString();
then call it in your adapter class.
first make interface listener inside listener make function with parameter like this
interface YourRecycleViewClickListener {
fun onItemClickListener(param1:View, param2: String)
}
now extend your activity
class YourActivity:YourRecycleViewClickListener{
override fun onItemClickListener(param1:View, param2: String) {
//do any thing
}
}
third step make interface constract in your recycle adapter
class YourAdapter(
private val listener: YourRecycleViewClickListener){
holder.constraintLayout.setOnClickListener{
listener.onItemClickListener(param1,param2)
}
}
this is by kotlin lang
and by java is same but change syntax
that all to do
I am designing a RecyclerView list. Each item of the Recyclerview contains a LinearLayout. This LinearLayout contains two views, the first one is an EditText and the second one is Button. When user taps on the button, it fires an onclick event. From onClick listener, I need to get the content of the EditText. I don't find a way to access the content of a sibling view when the user taps on another sibling view.
My question is not "how can I set on click listener to a button inside adapter". Most of the people answered how to set onClick listener to a button which is there inside the recyclerview item. My question is bit different, when I am inside onClick method which is fired from button, how will I access the edittext which is a sibling of button. Every item has one edittext, so when I click on a button how will I find the correct edittext?
For example, I have a recylerview of size 10. And each item of recyclerview contains a LinearLayout and inside linearlayout two item, one is an Edittext and the other one is a Button. when I tap on 7th items button, how will I get the text of 7th item's Edittext? I hope I have explained it well
Any help would be appreciated.
First of, you need two references: one to your EditText and one to your Button. You can get those in your ViewHolder. Next, you need an OnClickListener. The ViewHolder can conveniently also implement one but you could also use onBindViewHolder() for that.
Inside that OnClickListener you can filter out your id with a switch statement if you want to and then get the content of the EditText like this:
switch(viewId) {
case R.id.buttonId:
String text = editText.getText().toString();
// do something with that text
return true;
}
In case you implemented an OnClickListener in your ViewHolder you can then do this button.setOnClickListener(this); inside your ViewHolder to make sure onClick() is actually called when you click the button.
EDIT:
Here's some sample code that should work for your case. I'm implementing View.OnClickListener here as mentioned above.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
EditText editText;
Button button;
public ViewHolder(View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editText);
button = itemView.findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button:
String text = editText.getText().toString();
break;
}
}
}
This is what it would look like if you were to do it in your onBindViewHolder() (in this case you would NOT implement the OnClickListener in your ViewHolder obviously):
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = holder.editText.getText().toString();
}
});
}
Step 1 :Make an abstract function in your adapter.
abstract void onButtonClicked(String text);
Step 2: Declare your adapter Abstract.
Step 3: Override the method (onButtonClicked(String text);) in your activity were you have instantiated the adapter.
Step 4: In your adapter inside the onClickListener for your button call the function :
onButtonClicked(editText.getText().toString());
and you'll get the string in your activity where you overrided the method.
You can use holder pattern for RecylcerView adapter. Then you can set click listener on your button and get the text from EditText.
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = simpleEditText.getText().toString()
}
});
}
}
You can do it inside your adapter which is being set on the recycler view.
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
}
}
And in the bindview holder you can access the views
public void onBindViewHolder(#NonNull final ImageAdapter.MyViewHolder holder, int position) {
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Your Code to access the edit text content
}
});
}
use a custom listener like this in the holder:
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView, final OnItemSelectedListener listener) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String text = simpleEditText.getText().toString();
if(listener != null) listener.onItemSelected(text);
}
});
}
public interface OnItemSelectedListener{
void onItemSelected(String value);
}
}
Simply Use Your ViewHolder. It contains all the children you want. Implement the code inside your adapter where each item is inflated. Here is an example.
//inside the onBindViewHolder
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = viewHolder.editText.getText().toString();
Log.d("output", text);
}
});
If you are using FirebaseUI Implement this inside the populateViewHolder for older version and onBindViewHolder for the later versions.
People put -1 when they don't know the answer or when they do not understand question. So funny!! In onclick I took parent(getParent()) from the view and accessed the second child of the parent. With that I am able to access the content of the sibling.
` public void onClick(View v) {
for(int i = 0;i<parent.getChildCount();i++){
if(parent.getChildAt(i)instanceof EditText){
passwordView = (EditText)parent.getChildAt(i);
}
}
}`
Question:
I'm adding views into a recyclerview with a click. When I click a view it opens a DialogFragment, how do I remove that view through the DialogFragment (by clickign on a button inside it)?
Adapter:
public class SubjectsAdapter extends RecyclerView.Adapter<SubjectsAdapter.ViewHolder> {
public List<String> items = new ArrayList<>();
public Activity mcontext;
public SubjectsAdapter(Activity context) {
this.mcontext=context;
}
public void addItem(String name) {
items.add(name);
notifyItemInserted(items.size() - 1);
}
public void removeItem(int position) {
items.remove(position);
notifyItemRemoved(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.grid_item_button, parent, false);
view.requestFocus();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setButtonName(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
int i = 100;
public EditText EditName;
class ViewHolder extends RecyclerView.ViewHolder{
public Button GridButton;
public SharedPreferences prefs;
public ViewHolder(View itemView) {
super(itemView);
GridButton = (Button) itemView.findViewById(R.id.grid_button);
EditName = (EditText) itemView.findViewById(R.id.editName);
ClassName = (TextView) itemView.findViewById(R.id.ClassName);
prefs = mcontext.getPreferences(Context.MODE_PRIVATE);
GridButton.setId(++i);
EditName.requestFocus();
//Showing the DialogFragment
GridButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Fragment_Subject_Edit editFragment = Fragment_Subject_Edit.newInstance();
Bundle data = new Bundle();
data.putInt("ID", v.getId());
editFragment.setArguments(data);
editFragment.show(mcontext.getFragmentManager(), "Title");
return false;
}
});
}
public void setButtonName(String buttonName) {
GridButton.setText(buttonName);
}
}
}
Adding views in the activity:
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
final SubjectsAdapter adapter = new SubjectsAdapter(this);
recyclerView.addItemDecoration(new SampleItemDecoration());
recyclerView.setAdapter(adapter);
recyclerView.setItemViewCacheSize(15);
recyclerView.setNestedScrollingEnabled(false);
#Override
public void onClick(View v) {
adapter.addItem(prefs.getString("key1", null));
}
What I have from Lucas Crawford answer, although I'm not getting it right:
1:
public Activity mcontext;
public View.OnLongClickListener LongClicking;
public SubjectsAdapter(Activity context, View.OnLongClickListener longClick) {
this.mcontext = context;
this.LongClicking = longClick;
}
2:
View.OnLongClickListener LongClicker;
...
...
...
adapter = new SubjectsAdapter(this, LongClicker);
recyclerView.setAdapter(adapter);
3:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.grid_item_button, parent, false);
view.setOnLongClickListener(LongClicking);
return new ViewHolder(view);
}
4:
fm = getFragmentManager();
ClassEditor = new Fragment_Subject_Edit();
LongClicker = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Bundle data = new Bundle();
data.putInt("ID", v.getId());
ClassEditor.setArguments(data);
ClassEditor.show(fm, "Title");
return false;
}
};
Nothing happens when I longClick the button, nor anywhere in the view, what's wrong with these steps, and how to do number 5?
Easy Solution
Instead of assigning the onLongClickListener in the ViewHolder, I would assign the click listener as part of the constructor in the adapter's creation. This way, when you create the view holder in onCreateViewHolder, you give the new view for the view holder the adapter's passed click listener. This is better since it decouples the click event from the ViewHolder's work, as well as letting the activity that created the adapter handle what happens when clicked. (also the dialog fragment created is tied to an Activity lifecycle, why not create it there!).
Next, add a click listener to the dialog fragment's creation, possible as a member variable with a getter/setter. The button in the fragment is then assigned that click listener when you are inflating the dialog fragments view. This way, you do all the click event listening within your Activity, and use the same strategy in both the adapter and dialog fragment.
Can provide code IF required. I hope that makes sense.
Here is a list of what I suggested:
Add a click listener to the constructor of the recycler view adapter.
Pass an onLongClickListener object when you are creating the adapter within your activity.
Assign your view the click listener passed to the adapter in onCreateViewHolder.
Within the click listener created in your activity for the adapter, create the dialog fragment and assign a NEW click listener to handle the button press you desire. This click listener also is apart of the Activity.
When inflating the views in the dialog fragment, give the target button the listener you assigned to the dialog fragment.
The logic of removing the view (or item) from the RecyclerView adapter would be in the click listener you assign to the new dialog fragment. You need a reference to the item currently being removed as well (which you do via arguments).
Advanced Solution
A more advanced solution would be to use something like EventBus which handles listening for events. It cleans up a lot of code to use this. Another one is Otto by Square. It does the same thing, and I personally use Otto for event driven listening rather than passing around click listeners. You can decouple the need for a click listener being passed to your recycler's adapter by just setting a click listener in the adapter that posts an event that your activity is listening for, which then triggers the dialog fragment creation. The dialog fragment would then do the same thing by creating and assigning a new listener within the fragment that posts another event that your activity is listening for related to removing the particular adapter item.
I'm using Picasso in onBindViewHolder but when scrolling up or down it reload same images urls from internet this make the list so bad and slow
so i want when it first load save the scroll state for images and do not load it again '
how i can do that?
onBindViewHolder Method :
#Override
public void onBindViewHolder(MyCustomAdapter.CustomViewHolder holder, int position) {
Dishes di = dish.get(position);
//Download image using picasso library
Picasso.with(mContext).load(di.getDishImageUrl())
.error(R.drawable.ic_error)
.placeholder(R.drawable.fav_btn)
.into(holder.imageView);
//Setting text view title
holder.textView.setText(Html.fromHtml(di.getDishName()));
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomViewHolder holder = (CustomViewHolder) view.getTag();
int position = holder.getPosition();
Dishes di = dish.get(position);
Toast.makeText(mContext, di.getDishName(), Toast.LENGTH_SHORT).show();
}
};
//Handle click event on both title and image click
holder.textView.setOnClickListener(clickListener);
holder.imageView.setOnClickListener(clickListener);
holder.textView.setTag(dish.get(position));
holder.imageView.setTag(dish.get(position));
}