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 : Since this answer has gotten some love over the years, here is what I would use now. This removes the coupling between the Fragment and the Adapter as in my older solution below.
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 :
and update the constructor of the Adapter :
then you call methods using the fragment variable.
I know it's late to answer but There are 2 ways more to do it:
You can also send
broadcast
fromadapter
and register it infragment
.Use interface. Refer this SO question for details.
You can make sendData method as static
n call it as