gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 09:40:58 24 4
gpt4 key购买 nike

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

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

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

最佳答案

这是解决方案,将一个标志传递给您 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 以避免异常。

更新:

如果你有两个ViewHolder:

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

关于android - 在方向更改时更改 RecyclerView 的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com