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

时间:2016-10-05 07:00:14

标签: android android-recyclerview android-orientation gridlayoutmanager

RecyclerView GridLayoutManager。我正在为风景显示单列,为风景显示七列。 使用:

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

但问题是用于肖像的布局对于风景来说是不可行的。 那么如何在配置更改时更改RecyclerView的布局。 或者还有其他解决方案吗?

1 个答案:

答案 0 :(得分:2)

以下是此解决方案,向您Adapter传递一个描述当前方向的标记。

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

在适配器类中:

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

确保正确处理View 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;
    }

在Bind 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
    }
}