TOP
TOP

Reputation: 2624

How to make ViewHolder listen to screen orientation change?

I want to notify all ViewHolder of RecyclerView when the screen orientation is changed. I can notify the ViewHolder that are on screen. But for the ones that are out of screen I don't know how to notify them. Please help.

Upvotes: 0

Views: 920

Answers (2)

6rchid
6rchid

Reputation: 1302

You can get orientation by using getResources() in your Adapter/ViewHolder. Depending on how you get it, the ViewHolder View passed to the constructor can give you just that:

private HeaderViewHolder(View itemView) {
    super(itemView);
    int mOrientation = itemView.getResources().getConfiguration().orientation;
}

or through the onCreateViewHolder:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
    Context mContext = viewGroup.getContext();
    int mOrientation = mContext.getResources().getConfiguration().orientation;
    ...
}

This value should change when the screen is rotated.

Upvotes: 0

Oussema Aroua
Oussema Aroua

Reputation: 5339

add this to your activity to get the orientation changing :

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        //PORTRAIT MODE
        adapter.screenChanged("PORTRAIT");
    } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //LANDSCAPE MODE
        adapter.screenChanged("LANDSCAPE");
    }
}

add this to your adapter

 public void screenChanged(String orientation){
        if (orientation.equals("PORTRAIT")){
            //code
        }else{
            //code
        }
    }

Upvotes: 0

Related Questions