How can I update ActionBar title from Adapter?
I tried this:
((MainActivity) getActivity()).getSupportActionBar().setTitle(getString(R.string.home_item));
but this way only works within fragments. So I do this:
((MainActivity) view.getContext()).getSupportActionBar().setTitle(getString(R.string.home_item));
and get cast exception. I don't know how to do it.
So it is possible to update ActionBar Title from Adapter? Thanks
pass the activity context in your adapter.
Myadapter adapter = new Myadapter (this);
In Myadapter class:
Context context;
public Myadapter(Context c){
this.context = c;
}
Now use context
to set the title like:
((MainActivity) context.getSupportActionBar().setTitle(getString(R.string.home_item));
Maybe something like a callback structure? With this you don't need to pass an instance of your whole Context
but just the callback.
class Adapter{
private AdapterCallback callback;
public Adapter(AdapterCallback callback){
this.callback = callback;
}
public interface AdapterCallback{
void changeTitle(String s);
}
}
And your Activity implements AdapterCallback
and pass it to the Adapter like
class YourActivity extends Activity implements AdapterCallback{
Adapter adapter = new Adapter(this);
public void changeTitle(String s){
getSupportActionBar().setTitle(s);
}
}
With that you can simply call in your Adapter class
callback.changeTitle("New Title");