Android Update toolbar/actionbar title from Adapte

2019-06-10 05:43发布

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

2条回答
Viruses.
2楼-- · 2019-06-10 06:12

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");
查看更多
男人必须洒脱
3楼-- · 2019-06-10 06:23

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));
查看更多
登录 后发表回答