Call a Fragment method from an Adapter - java

I have a method sendData() in my fragment. This method starts a new Activity. I want to call this method from my ArrayAdapter.
Here is my code:-
HomeFragment.java
stagAdaper = new StaggeredAdapter(myContext, android.R.layout.simple_list_item_1, getList);
mGridView.setAdapter(stagAdaper);
private void sendData(int position)
{
myDialog = new ProgressDialog(myContext).show(getActivity(), "Fetching news..", "Just a moment");
myDialog.getWindow().setContentView(R.layout.openarticlewaitprogress);
myDialog.getWindow().setTitle("Loading..");
myDialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
new NewsDetails(myDialog);
Intent nIntent = new Intent(getActivity(),Details.class);
String Body=getList.get(position).getBody();
newsIntent.putExtra("Body", Body);
startActivity(nIntent);
}
StaggeredAdapter.java
viewHolder.layGridLayout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//viewHolder.layGridLayout.setForeground(R.drawable.foreground_selector);
}
});
return convertView;
}
How can I do it?

Edit :
Here is what I would use now. Older, "easier" solutions are available below.
MyFragment extends Fragment implements CustomAdapter.EventListener {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
CustomAdapter adapter = new CustomAdapter(..., this);
}
void onEvent(int data) {
doSomething(data);
}
}
CustomAdapter extends BaseAdapter {
EventListener listener;
public interface EventListener {
void onEvent(int data);
}
public CustomAdapter(..., EventListener listener) {
this.listener = listener;
}
...
}
Now from any place in the adapter we can call listener.onEvent(data); to trigger the method in the fragment.
Moreover, instead of providing a listener through the constructor, we can add another method in the adapter such as registerListener(EventListener eventListener) and then maintain a list of listeners if needed.
Old Answer:
Solution 1 :
Make the adapter an inner class of your fragment, so that you can call the method directly.
Solution 2 :
Update your adapter constructor to accept the Fragment as a parameter.
Something like :
customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1, getList, HomeFragment.this);
and update the constructor of the Adapter :
public CustomAdapter(Context context, int id, HomeFragment fragment) {
this.fragment = fragment;
}
then you call methods using the fragment variable.
fragment.doSomething();

I know it's late to answer but There are 2 ways more to do it:
You can also send broadcast from adapter and register it in fragment.
Use interface. Refer this SO question for details.

You can make sendData method as static
public static void sendData(int position)
{
......
}
n call it as
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
HomeFragment.sendData(position)
........
}

Related

Passing data from RecyclerView to Fragment?

I am currently creating an application which consists of a Fragment, an Adapter for a RecyclerView and a RecyclerView which is accessed through the fragment. I need data to be passed from the RecyclerView back to the fragment however am unable to do so as the Fragment isn't identified through the Intent. When the user selects an item from the RecyclerView this item should be then passed through to the fragment. I have the RecyclerView using onBackPressed() in order to navigate back to the fragment which works fine, however no data seems to pass. Please see below what I currently have:
CustomAdapter.java
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.text1.setText(String.valueOf(text1.get(position)));
holder.text2.setText(String.valueOf(text2.get(position)));
holder.text3.setText(String.valueOf(text3.get(position)));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(v, holder.getAdapterPosition());
}
});
}
InputToFragment.java
#Override
public void onItemClick(View view, int position) {
// Need to pass data through to Fragment, however unable to do so as it's not identified
// within the Intent
onBackPressed();
}
});
Fragment.java
// Nothing related to Passing data within the Fragment
Its for your fragment
YourFragment : Fragment() {
OnItemClickListener listener = new OnItemClickListener(){
#Override
public void onItemClick(View view, int position){
//this called if item at adapter clicked
}
}
....
//whatever lifecycle you choose for initialize adapter
onCreateView(){
adapter = new YourAdapter(listener);
}
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
}
and this for your adapter
private OnItemClickListener listener;
YourConstructorAdapter(OnItemClickListener listener){
this.listener = listener;
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.text1.setText(String.valueOf(text1.get(position)));
holder.text2.setText(String.valueOf(text2.get(position)));
holder.text3.setText(String.valueOf(text3.get(position)));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// this code calling method from fragment
listener.onItemClick(v, position);
}
});
I'm highly recommend migrate to kotlin and use higher-order function, its very simple.
You can use interface, here is how to do it
create interface to handle click:-
public interface OnCustomItemSelectListener {
void onCustomItemSelected(String data);
}
not extend it in your fragment or activity:-
public class MyActivity implements OnCustomItemSelectListener {
#Override
public void onCustomItemSelected(String data) {
/*store it if neede */
/* additional code */
}
}
In recycler view pass this activity to recycler view constructor and inside your custom adapter you can assign this activity to listener interface and call the onCustomItemSelected method from overridden onClick(), which will be in your previous activity or fragment.
OnCustomItemSelectListener itemSelectListener;
public CustomAdapter(Activity listenerAct, .....){
this.itemSelectListener = listenerAct;
}
#Override
public void onClick(View view)
{
itemSelectListener.onCustomItemSelected(data);
}
this will pass data to onCustomItemSelected() method in your fragment/activity

How can I pass a ArrayList<String> created in a fragment to the main activity

I have a drawer menu with 3 items (Restaurant, Movie, Food). They are basically 3 to do lists. Each list has its on fragment and in the view there is a way to add items to the list.
The restaurant list, the movie list ad the groceries list.
I need to be able to share that list (via any share-channel) by clicking the share icon that is in the toolbar.
This is my fragment where i populate the items list that i want to use when i click the share icon that is on the toolbar. Basically i need to pass "items" to the MainActivity and use it.
package com.example.mylists;
import android.content.Intent;
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "FoodFragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onCreateView ");
View view = inflater.inflate(R.layout.fragment_food, container, false);
lvItems = (ListView) view.findViewById(R.id.lvItems);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
if (items.isEmpty())
items.add("Dummy Item");
final EditText newTask = (EditText) view.findViewById(R.id.etNewItem);
Button btnAdd = (Button) view.findViewById(R.id.btnAddItem);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemText = newTask.getText().toString();
itemsAdapter.add(itemText);
newTask.setText("");
writeItems();
Log.i(TAG, "in on send data ");
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onViewCreated ");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "in on onActivityCreated ");
super.onActivityCreated(savedInstanceState);
OnItemLongClickListener listener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
//Log.i(TAG, "in on onItemLongClick ");
//Toast.makeText( getActivity().getBaseContext() , "Long Clicked " , Toast.LENGTH_SHORT).show();
items.remove(position);
itemsAdapter.notifyDataSetChanged();
writeItems();
//return true;
return false;
}
};
lvItems.setOnItemLongClickListener(listener);
}
private void readItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should declare ArrayList<String> items in your MainActivity. Then create a public setter method for items.
public void setItems(ArrayList<String> items){
this.items = items;
}
Then you should call setItems() method in your fragment.
((MainActivity) getActivity()).setItems(items);
Interface for Callback
interface MyInterface {
void setItems(ArrayList<String> items);
}
In your activity:
class MyActivity {
ArrayList<String> items;
MyInterface itemsCallback = new MyInterface(){
#Override
void setItems(ArrayList<String> items){
this.items = items;
}
}
myFragment.setItemsCallback(itemsCallback);
}
And then in fragment
class MyFragment {
private MyInterface itemsCallback;
public void setItemsCallback(MyInterface itemsCallback){
this.itemsCallback = itemsCallback;
}
private void readItems(){
...
itemsCallback.setItems(items);
}
}
I guess it's better then public setter in MainActivity. Because, you know, it's like more SOLID code. In this case your Fragment doesnt hold reference to Activity and doesnt even know about it existence.
1.Define an interface , 2.Let your Activity implements the interface 3.use (interface)getActivity() to cast your Activity to that interface,then you can call the method in the interface to send your ArrayList "items"

Accessing a list from a different fragment

So I have my MainActivity.java, I also have a FragmentA.java and a FragmentB.java.
In my MainActivity I have a BottomNavigation which allows me to switch between the two fragments.
MainActivity.java
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_a:
selectedFragment = new FragmentA();
break;
case R.id.nav_b:
selectedFragment = new FragmentB();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
Inside FragmentA I have a RecyclerView with an adapter of course and on each CardView there is a button, when i click that button i want to pass the corresponding object to the RecyclerView in FragmentB.
FragmentA.java
adapter.setOnItemClickListener(new RewardItemAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//When I click the item, pass theItem to FragmentB
CustomObject theItem = items.get(position);
}
});
FragmentB.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
itemsList = new ArrayList<>();
itemsList.add(new CustomObject(R.drawable.picture, "Text", "More text.", 200));
//I'm guessing I want to add the CustomObject that I clicked to the list here so that I can display it in the RecyclerView
recyclerView = v.findViewById(R.id.fragmentBRecyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
adapter = new FragmentBItemAdapter(itemsList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
return v;
}
The only issue is I have no idea how to, I tried using Interfaces but I couldn't implement it properly, I'm not sure if it's because I am instantiating a new instance of the fragments.
You could achieve this by two ways:
1) Through Interface Contract between the Fragment and Activity
class FragmentA: Fragment() {
interface SomeInterfaceName {
fun setSelectedItem(item: SomeItem)
}
}
class FragmentA: Fragment() {
interface AnotherInterfaceName {
fun getSelectedItem(): SomeItem
}
}
class ContainerActivity: Activity(), AnotherInterfaceName, SomeInterfaceName {
var someItem: SomeItem? = null
fun setSelectedItem(item: SomeItem) {
someItem = item
// inflate your FragmentB
}
fun getSelectedItem(): SomeItem {
return someItem;
}
}
But the best solution in my opinion is to use a shared ViewModel for this case.
You can read about this he here under "Share data between fragments" section.
Doing the job by interface is correct, But you have to bind it to the Fragment in the onAttached lifeCycle method.
Define an Interface. OnFragmentInteractionListener.java
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String args);
}
Then Implement your activity with the interface.
public class MainActivity extends ActionBarActivity implements OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
onFragmentInteraction(String args){
**// Made the Change Here**
// Send Local Broadcast Receiver
Intent intent = new Intent("UPDATE_LIST");
intent.putExtra("TYPE", 0);
// Change the args to get position or the relevant param
intent.putExtra("POSITION", selectedPosition);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
In the FragmentA.java,
public class FragmentA extends Fragment {
OnFragmentInteractionListener mCallback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
...
adapter.setOnItemClickListener(new RewardItemAdapter.OnItemClickListener()
{
#Override
public void onItemClick(int position) {
//When I click the item, pass theItem to FragmentB
CustomObject theItem = items.get(position);
// Send the selected Item Name to Main Activity through args
mCallback.onFragmentInteraction(theItem.getName);
}
});
}
On your FragmentB.java class add Local Broadcast Receiver
public class FragmentBt extends Fragment{
public static Fragment newInstance(){
...
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout, container, false);
return v;
}
...
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
// Register Local Broadcast Receiver
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mMessageReceiver, new IntentFilter("UPDATE_LIST"));
}
#Override
public void onDestroy() {
super.onDestroy();
// Destroy the Local Broadcast Receiver
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mMessageReceiver);
}
// Create Broadcast Receiver instance
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra("POSITION")){
mAdapter.notifyItemChanged(intent.getIntExtra("POSITION", 0));
// Update Adapter as the requirement
}
}
};
}
Hope this will help.
Cheers!!

Interface value is always null

I am using custom recycler view and in adapter class i have implemented interface which is always null on button click. Here is my adapter class.
public class FeedListAdapter extends
RecyclerView.Adapter<AddtoCartHolder> {
private OnFeedItemClickListener onFeedItemClickListener;
public FeedListAdapter(Activity activity, ArrayList<CartItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
this.filteredfeedItems = feedItems;
inflater = LayoutInflater.from(activity);
}
public void setOnFeedItemClickListener(OnFeedItemClickListener onFeedItemClickListener) {
this.onFeedItemClickListener = onFeedItemClickListener;
}
#Override
public AddtoCartHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.feed_item, parent, false);
AddtoCartHolder viewHolder = new AddtoCartHolder(v);
setupClickableViews(v, viewHolder);
return viewHolder;
}
#Override
public void onBindViewHolder(final AddtoCartHolder holder, int position) {
CartItem item = (CartItem) filteredfeedItems.get(position);
holder.price.setText((String.valueOf(item.getProductName()) + ""));
holder.location.setText((String.valueOf(item.getQuantity())) + "");
}
private void setupClickableViews(final View view, final AddtoCartHolder cellFeedViewHolder) {
cellFeedViewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onFeedItemClickListener !=null){
onFeedItemClickListener.onAddClick(v, cellFeedViewHolder.getAdapterPosition());
}
else{
Toast.makeText(activity, "Data is null", Toast.LENGTH_LONG).show();
}
}
});
}
public interface OnFeedItemClickListener {
void onAddClick(View v, int position);
}
#Override
public int getItemCount() {
return filteredfeedItems.size();
}
I am always getting null whenever clicking on button really down know why it is coming null...
Here is my fragment class which have implemented interface.
public class MyFragment extends Fragment implements FeedListAdapter.OnFeedItemClickListener{
// the method
#Override
public void onAddClick(View v, int position) {
// TODO Auto-generated method stub
Snackbar.make(clContent, "Product removed from cart!",
Snackbar.LENGTH_SHORT).show();
}
You must be instantiating a FeedListAdapter in your fragment correct buddy ???
Like using statement :
FeedListAdapter adapter = new FeedListAdapter(this.getActivity(),your_array_list)
After instantiating your adapter just call your adapter's setOnFeedItemClickListener with 'this' as argument :) That's all :)
adapter.setOnFeedItemClickListener(this)
Hope my answer helped you :) Happy coding buddy :)
By the looks of things your aren't setting your listener. Thus, onFeedItemClickListener is always null.
Also MyFragment isn't actually doing anything, you haven't inflated a view, overridden onCreateView(...), etc.
There's a few things that you could definitely change to improve your implementation. But to get your listener working:
Just get rid of MyFragment you don't appear to be using it properly.
Move your implements FeedListAdapter.OnFeedItemClickListener to your Activity. i.e. Make your Activity implement your OnFeedItemClickListener interface rather than MyFragment (which doesn't appear to be doing anything).
Make FeedListAdapter set the listener in its constructor:
public FeedListAdapter(Activity activity, ArrayList<CartItem> feedItems)
{
this.activity = activity;
// Assume we the activity implements OnFeedItemClickListener
setOnFeedItemClickListener((OnFeedItemClickListener)activity);
this.feedItems = feedItems;
this.filteredfeedItems = feedItems;
inflater = LayoutInflater.from(activity);
}
Please keep in mind that this is a pretty bad implementation and you can definitely improve on it but for the purpose of the question, it's sufficient.

How to create interface between Fragment and adapter?

I have fragment with ListView, say MyListFragment, and custom CursorAdapter.
I'm setting onClickListener in this adapter for the button in the list row.
public class MyListAdapter extends CursorAdapter {
public interface AdapterInterface {
public void buttonPressed();
}
...
#Override
public void bindView(final View view, final Context context, final Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
...
holder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// some action
// need to notify MyListFragment
}
});
}
}
public MyListFragment extends Fragment implements AdapterInterface {
#Override
public void buttonPressed() {
// some action
}
}
I need to notify fragment when the button is pressed. How to invoke this interface?
Help, please.
Make a new constructor and an instance variable:
AdapterInterface buttonListener;
public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
When the Adapter is made, the instance variable will be given the proper reference to hold.
To call the Fragment from the click:
public void onClick(View v) {
buttonListener.buttonPressed();
}
When making the Adapter, you will have to also pass your Fragment off to the Adapter. For example
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
since this will refer to your Fragment, which is now an AdapterInterface.
Keep in mind that on orientation of the Fragment changes, it will most likely be recreated. If your Adapter isn't recreated, it can potentially keep a reference to a nonexistent object, causing errors.
Using Eventbus:
Examples:
https://github.com/kaushikgopal/RxJava-Android-Samples/tree/master/app/src/main/java/com/morihacky/android/rxjava/rxbus
or
https://github.com/greenrobot/EventBus
Using Interfaces:
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 a Fragment.
Create Callback Interface:
public interface AdapterCallback {
void onMethodCallback();
}
Passing in Callback/Fragment:
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.
In your Fragment:
public class MyFragment extends Fragment implements AdapterCallback {
private MyAdapter mMyAdapter;
#Override
public void onMethodCallback() {
// do something
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mMyAdapter = new MyAdapter(this); // this class implements callback
}
}
Use the Callback in your Adapter:
In the Fragment, 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 mAdapterCallback;
public MyAdapter(AdapterCallback callback) {
this.mAdapterCallback = callback;
}
#Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, final int i) {
// simple example, call interface here
// not complete
viewHolder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mAdapterCallback.onMethodCallback();
}
});
}
}
or Use the Fragment in your Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private AdapterCallback mAdapterCallback;
public MyAdapter(Fragment fragment) {
try {
this.mAdapterCallback = ((AdapterCallback) fragment);
} catch (ClassCastException e) {
throw new ClassCastException("Fragment must implement AdapterCallback.");
}
}
#Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, final int i) {
// simple example, call interface here
// not complete
viewHolder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
mAdapterCallback.onMethodCallback();
} catch (ClassCastException exception) {
// do something
}
}
});
}
}
Follow the 2 steps below for receive callback from Adapter in Fragment (or Activity)
First: In your Adapter
public class ListAdapter extends RecyclerView.Adapter < RecyclerListAdapter.ItemViewHolder > {
...
private ListAdapterListener mListener;
public interface ListAdapterListener { // create an interface
void onClickAtOKButton(int position); // create callback function
}
public RecyclerListAdapter(Context mContext, ArrayList < Items > listItems, ListAdapterListener mListener) { // add the interface to your adapter constructor
...
this.mListener = mListener; // receive mListener from Fragment (or Activity)
}
...
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
holder.btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use callback function in the place you want
mListener.onClickAtOKButton(position);
}
});
...
}
...
}
Second: In your Fragment (or Activity), there are 2 ways for implement callback method
Way 1
public MyListFragment extends Fragment {
...
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
...
ListAdapter adapter = new ListAdapter(getActivity(), listItems, new ListAdapter.ListAdapterListener() {
#Override
public void onClickAtOKButton(int position) {
Toast.makeText(getActivity(), "click ok button at" + position, Toast.LENGTH_SHORT).show();
}
});
...
}
}
Way 2
public MyListFragment extends Fragment implements ListAdapter.ListAdapterListener {
...
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
ListAdapter adapter = new ListAdapter (getActivity(), listItems, this);
...
}
#Override
public void onClickAtOKButton(int position) {
Toast.makeText(getActivity(), "click ok button at" + position, Toast.LENGTH_SHORT).show();
}
}
This is very similar to the way an activity and a fragment should communicate. In the constructor of your adapter, pass a reference of your fragment, cast it to your interface and just call yourReference.buttonPressed() on your onClick method.
a solution for NPE is first to make conctractor in your Fragment like that
public MyFragment MyFragment(){
return this;
}
then initialize your listener is adapter like that
Lisener lisener = new MyFragment();
Make a constructor like that:
public MyAdapter(Activity activity,AlertMessageBoxOk alertMessageBoxOk) {
this.mActivity = activity;
mAlertMessageBoxOk = alertMessageBoxOk;
}
call the interface from adapter use any event
mAlertMessageBoxOk.onOkClick(5);
after that implement AlertMessageBoxOk interface to your fragment like this,
class MyFragment extends Fragment implements AlertMessageBoxOk {
#Override
public void onOkClick(int resultCode) {
if(resultCode==5){
enter code here
}
}
}

Categories