I am trying to show data in toolbar. I have recyclerview where I set movies name. when I click any movie name, the name show in toolbar. I defined the onclick method in adapter class.
This is adapter class
Make public method in adapter class and call that method in onClick
ExampleAdapter.java
holder.tvMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectMovie(list.get(holder.getAdapterPosition()).getname());
}
}
});
public void onSelectMovie(String movieName)
{
}
Override onSelectMovie method where you call the adapter constructor
exampleAdapter = new ExampleAdapter() {
#Override
public void onSelectMovie(String movieName) {
super.onSelectImage(movieName);
setTitle(movieName);
}
};
Related
In my android app I am using an Adapter inside another Adatper. Let's say child and parent Adapter. In parent Adapter I used onclick method on an item and instantiate the child Adapter. Now onClick on the view in child Adapter I want to send signal to parent Adapter and run a function..
This is my code:
// This is in parent layout
holder.liker.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
holder.reaction_layout.setVisibility(View.VISIBLE);
if(holder.cursor.getCount()>0)
{
holder.show_reaction=true;
holder.tinyDB.putString("post_id",String.valueOf(holder.username.getTag()));
holder.tinyDB.putString("act_id",String.valueOf(holder.post_comment.getTag()));
while(holder.cursor.moveToNext())
{
holder.imageModelArrayList.add(new ReactionModel(holder.cursor.getString(1),holder.cursor.getString(3),holder.cursor.getString(2)));
holder.recyclerView.setAdapter(holder.adapter); //Here i instantiate the child adapter
}
}
return true;
}
});
Now this is click function of child Adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tinyDB.putString("image",imageModelArrayList.get(position).getImage_drawable());
String react_id=String.valueOf(holder.title.getTag());
String act_id=tinyDB.getString("act_id");
String post_id=tinyDB.getString("post_id");
NetworkController.postLikePojoClassCall(base64,Integer.parseInt(act_id),Integer.parseInt(react_id),Integer.parseInt(post_id)).enqueue(new retrofit2.Callback<PostLikePojoClass>() {
#Override
public void onResponse(Call<PostLikePojoClass> call, retrofit2.Response<PostLikePojoClass> response) {
if(response.isSuccessful()) {
System.out.println("response__ " + response.body().getSuccess());
}else{
System.out.println("response__ " + response.errorBody());
}
}
#Override
public void onFailure(Call<PostLikePojoClass> call, Throwable t) {
System.out.println("failure__ " + t.getMessage());
}
});
}
});
In this click I want to send signal to parent Adapter that item has been clicked.
Use callback method to trigger your parent adapter
Create an interface
public interface MyInterface{
void click();
}
Make parent Adapter implement the interface
class YourParentAdapter extends RecyclerView.Adapter<YourViewHolder> implements MyInterface
Pass your parent adapter into the child adapter through the constructor
public ChildAdapter(MyInterface myInterface){
this.myInterface = interface;
}
Now you can use the function from parent Adapter inside the child Adapter:
myInterface.click();
I have in my MainActivity 3 RecyclerViews .
One of them in a bottom sheet and it is the main one (By Default the Bottom sheet is Open To Display this one ), in its adapter's onbind method I made an onClickListener so that I want when the user clicks on an item in it,
I want to go back to the main activity class to set To Start a method which it's rolled is to close the Bottom Sheet and set the data for the next recycling view (which will appear when the Bottom Sheet is closed)
..... The issue here is how to start this method from the onBind method's Listener and give it a parameter from this viewHolder as its name and some of its attributes
if there is something not clear please let me know
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.categoryImage.setImageResource(mRowOfCategories.get(position).getCategoryImage());
viewHolder.categoryName.setText(mRowOfCategories.get(position).getCategoryName());
viewHolder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
Easiest:
You declare the method you want to call in your Activity. It has to be public:
public void method(){}
Then, in the Constructor of the Adapter, you pass a reference to the Activity as a parameter:
public MyAdapter(Activity activity){}
And, in the onBindViewHolder:
MyActivity mActivity=(MyActivity)activity;
mActivity.method();
You can do that easily.
Define custom interface
public Interface CustomEventListener
{
public void MyEventListener(String message); //you can change parameters
}
In your adapter class
public Adapter ......... {
private CustomEventListener listener;
public void setListener(CustomEventListener listener)
{
this.listener = listener;
}
//Your onBind
Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.categoryImage.setImageResource(mRowOfCategories.get(position).getCategoryImage());
viewHolder.categoryName.setText(mRowOfCategories.get(position).getCategoryName());
viewHolder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.MyEventListener("Message");
}
});
}
}
In your Activity when create Adapter add this code
public void InitAdapter()
{
yourAdapter = new Adapter(); // bloa bla bla
yourAdapter.setListener(new CustomEventListener() {
public void MyEventListener(String message)
{
// then do what you want
}
}
}
You need to use Listener for handling the click in your Adapter something like this:
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
then call the listener with:
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
...
viewHolder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call the listener.
mListener.onItemClick(v, viewHolder.getAdapterPosition());
}
});
}
then when you're using the adapter, set the listener with something like this:
adapter.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(View view, int position) {
// do something with the view and position.
}
});
You want your recycleviews to be aware of each other. You'll need a class, maybe MainActivity, that will keep the selected value, also clear it upon request, in between recycleviews. Then you'll need that value to propagate the next recycleview. If you want to be efficient then you'll use one recycleview and swap the data in between selections, and animate it so it looks like a new recycleview is created.
I have an activity that creates a tab layout inside of it. The layout contains two fragments. The first fragment has a recycler view. Each card in the recycler view has a check box and a string.
If I click on the checkbox I want to send this card's string to a List located in the activity so I can populate it onto the second tab fragment.
On the first fragment cards I have an on click that sets boolean to true which is saved on an object. I am trying to figure out how to grab this object when it is clicked and send it to the activities list.
Activity-
public class MainActivity extends AppCompatActivity {
public static List toSendList = new ArrayList();
...more code
}
Recycler Adapter-
//initialize variables...
CheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (CheckBox.isChecked()) {
//MainActivity.toSendList.add(Obj);
obj.setIsChecked(true);
}
}
});
... more code
You might try EventBus and see if you like it. With it, you define an
'event' which can also be the object that you want to pass to your activity (or an event which wraps it). In the receiving activities, add your Subcribers. You then pass events/objects by calling
EventBus.getDefault().post(new CustomEvent());
and any place where a Subcriber is still attached will receive the event.
You can implement a listener which you will use on the Activity. For example:
You create a interface for a click listener.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.PhotoHolder> {
// ... all the code
public interface RecyclerViewOnClickListener(/* same arguments as above */);
}
On your view holder.
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View v) {
super(v);
// ... do all the initialization
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mOnClickListener(int position /* or whatever argument you like */)
}
}
On your RecyclerAdapter you store a listener for the click. So the adapter would end up with more code:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.PhotoHolder> {
// ... all the code
public interface RecyclerViewOnClickListener(/* same arguments as above */);
public RecyclerAdapter(RecyclerViewOnClickListener onClickListener) {
mOnClickListener = onClickListener;
}
}
So finally, in your Activity you just instantiate the RecyclerViewOnClickListener and pass it as an argument for the adapter.
try this :
Activity-
public class MainActivity extends AppCompatActivity {
public static List toSendList = new ArrayList();
...more code
public setPassData(String string)
{
//do something with this string
}
}
Fragment A/B
public void setPassData(String string)
{
((ActivityName)getActivity()).setPassData(string);
}
Recycler Adapter-
//initialize variables...
CheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (CheckBox.isChecked()) {
//MainActivity.toSendList.add(Obj);
obj.setIsChecked(true);
((FragmentName)mContext).setPassData(SomeStringToPass);
}
}
});
I have a Button on Listview and a custom adapter that loads the ListView. I want to call the Button onClickListner in main class not in the adapter class. how can i do this.
You can create one Global Interface
Like this
package com.radiofrance.interfaces;
public abstract class GlobalInterface implements eventInterface {
public void onClick(int values) {
}
public void onCancel() {
}
}
Then Implement this interface in Your Activity from which you call your adapter
public class SampleClickListener extends GlobalInterface {
#Override
public void onClick(final int values, final boolean state) {
}
}
now in your adapter pass this object of interface
Adapter adt = new Adpater(this, R.layout.row, arrRow,
new SampleClickListener());
and from your adapter call
listner.onClick(position, false);
Thanks
Is it possible to call method that is defined in Activity from ListAdapter?
(I want to make a Button in list's row and when this button is clicked, it should perform the method, that is defined in corresponding Activity. I tried to set onClickListener in my ListAdapter but I don't know how to call this method, what's its path...)
when I used Activity.this.method() I get the following error:
No enclosing instance of the type Activity is accessible in scope
Any Idea ?
Yes you can.
In the adapter Add a new Field :
private Context mContext;
In the adapter Constructor add the following code :
public AdapterName(......, Context context) {
//your code.
this.mContext = context;
}
In the getView(...) of Adapter:
Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof YourActivityName) {
((YourActivityName)mContext).yourDesiredMethod();
}
}
});
replace with your own class names where you see your code, your activity etc.
If you need to use this same adapter for more than one activity then :
Create an Interface
public interface IMethodCaller {
void yourDesiredMethod();
}
Implement this interface in activities you require to have this method calling functionality.
Then in Adapter getView(), call like:
Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof IMethodCaller) {
((IMethodCaller) mContext).yourDesiredMethod();
}
}
});
You are done. If you need to use this adapter for activities which does not require this calling mechanism, the code will not execute (If check fails).
You can do it this way:
Declare interface:
public interface MyInterface{
public void foo();
}
Let your Activity imlement it:
public class MyActivity extends Activity implements MyInterface{
public void foo(){
//do stuff
}
public onCreate(){
//your code
MyAdapter adapter = new MyAdapter(this); //this will work as your
//MyInterface listener
}
}
Then pass your activity to ListAdater:
public MyAdapter extends BaseAdater{
private MyInterface listener;
public MyAdapter(MyInterface listener){
this.listener = listener;
}
}
And somewhere in adapter, when you need to call that Activity method:
listener.foo();
Original:
I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.
In your Activity:
This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.
public class MyActivity extends Activity implements AdapterCallback {
private MyAdapter myAdapter;
#Override
public void onMethodCallback() {
// do something
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myAdapter = new MyAdapter(this);
}
}
In your Adapter:
In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private AdapterCallback adapterCallback;
public MyAdapter(Context context) {
try {
adapterCallback = ((AdapterCallback) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement AdapterCallback.", e);
}
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
// simple example, call interface here
// not complete
viewHolder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
adapterCallback.onMethodCallback();
} catch (ClassCastException e) {
// do something
}
}
});
}
public static interface AdapterCallback {
void onMethodCallback();
}
}
Basic and simple.
In your adapter simply use this.
((YourParentClass) context).functionToRun();
For Kotlin:
In your adapter, simply call
(context as Your_Activity_Name).yourMethod()
One more way is::
Write a method in your adapter lets say
public void callBack(){}.
Now while creating an object for adapter in activity override this method.
Override method will be called when you call the method in adapter.
Myadapter adapter = new Myadapter() {
#Override
public void callBack() {
// dosomething
}
};
In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:
class MyAdapter(val adapterOnClick: (Any) -> Unit) {
fun setItem(item: Any) {
myButton.setOnClickListener { adapterOnClick(item) }
}
}
class MyActivity {
override fun onCreate(savedInstanceState: Bundle?) {
var myAdapter = MyAdapter { item -> doOnClick(item) }
}
fun doOnClick(item: Any) {
}
}
For kotlin you could do something like :
if(context is MainActivity){ context.functionToCall(values) }
if (parent.getContext() instanceof yourActivity) {
//execute code
}
this condition will enable you to execute something if the Activity which has the GroupView that requesting views from the getView() method of your adapter is yourActivity
NOTE : parent is that GroupView