Reputation: 3815
I have followed this. I want to refresh the Activity
from Fragment
. I have back button in toolbar
for Fragment
to Activity
communication.
Here is my code for button listener and refresh the activity. I include this in fragment class:
final Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Handler().post(new Runnable() {
@Override
public void run()
{
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().overridePendingTransition(0, 0);
getActivity().finish();
getActivity().overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
});
This works fine, but it completly reload the app. What can be done here, so that I can avoid the reload operation and just refresh the activity?
Upvotes: 0
Views: 9817
Reputation: 11921
Define a method which do refresh operations in your activity.
public void refreshMyData(){
// do your operations here.
}
And in your onClick method:
final Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// If you use a generic toolbar you have to check instance of getActivity before cast.
((YourActivity)getActivity()).refreshMyData();
}
});
Edit: I refactored the code. I think you do not need post in onClick method.
Upvotes: 3
Reputation: 3825
Put this in your fragment
public void refreshActivity(){
ActivityName mDashboardActivity = (ActivityName) getActivity();
if(ActivityName!=null){
ActivityName.refreshMyData();
}
}
and put refreshMyData in your Activity
public void refreshMyData(){
//Code to refresh Activity Data hear
}
Let me know if not Working
Upvotes: 0
Reputation: 2819
Use callback(interface) to communicate with activity from fragment and don't use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK because it will clear your stack.
ex.
Fragment{
CallBack callback;
// your button click
onClick(){
callBack.mesage("Hi Activity");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if ( context instanceof Callback ) {
callback = (Callback) context;
} else {
throw new RuntimeException(context.getClass().getSimpleName()
+ " must implement Callback");
}
}
public interface Callback(){
void message(String message);
}
Activity implements Callback{
@Overide
public void message(String message){
System.out.println(message);
// to refresh activity
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
}
Upvotes: 5