在方向更改时更改 RecyclerView 的布局

Change RecyclerView's Layout on orientation change

我有 RecyclerViewGridLayoutManager。我正在显示横向的单列和横向的七列。 使用:

 @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        recyclerViewCalender.setLayoutManager(new GridLayoutManager(this, newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 7 : 1));
        super.onConfigurationChanged(newConfig);
    }

但问题是用于纵向的布局不适用于横向。 那么如何在配置更改时更改 RecyclerView 的布局。 或者有什么其他的解决办法吗??

这里是这个问题的解决方案,传递一个 Flag 给你 Adapter 描述当前方向。

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    //Update the Flag here
    orientationLand = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? true : false);
}

在您的适配器中 class:

@Override
public CalenderSessionHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    //User Flag here to change layou
    View itemView = LayoutInflater.from(parent.getContext()).inflate(orientationLand ? R.layout.item_calender_session_land : R.layout.item_calender_session_port, null);
    return new CalenderSessionHolder(itemView);
}

确保正确处理视图 ID 以避免异常。

更新:

如果您有两个 View Holder:

@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        if (orientationLand)
        {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_calender_session_land , parent, false);
            return new LandViewHolder(v);
        }
        else
        {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_calender_session_port, parent, false);
            return new PortViewHolder(v);
        } 
        return null;
    }

在绑定ViewHolder

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
    if (holder instanceof PortViewHolder)
    {
        PortViewHolder portHolder = (PortViewHolder) holder;
        //Initialize Views here for Port View
    } else if (holder instanceof LandViewHolder)
    {
        LandViewHolder landViewHolder = (LandViewHolder) holder;
        //Initialize Views here for Land View
    }
}