Android Update toolbar/actionbar title from Adapter

余生长醉 提交于 2019-12-22 01:31:21

问题


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


回答1:


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));



回答2:


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");


来源:https://stackoverflow.com/questions/42788882/android-update-toolbar-actionbar-title-from-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!