项目的Fragment比较简单,除了标题栏就一个网络数据显示的RecyclerView,Adapter Item layout对应了不同的xml文件,分别在layout_port(竖屏)、layout_land(横屏)、layout(默认)文件夹下。但切换时发现,Adapter Item layout并未发生变化。
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gift_record, container, false);
view.findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoExchangeGiftFragment();
}
});
recyclerView = view.findViewById(R.id.record);
final GiftRecordAdapter adapter = new GiftRecordAdapter();
recyclerView.setAdapter(adapter);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
int mCurrentOrientation = getResources().getConfiguration().orientation;
if ( mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT ){
layoutManager.setOrientation(OrientationHelper.VERTICAL);
}else {
layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
}
TYGameSDKManager.getInstance().giftRecord(new Listener<List<GiftRecord>>() {
@Override
public void success(List<GiftRecord> res) {
Log.d("test", "gift record success");
adapter.setData(res);
}
@Override
public void fail(String reason) {
Log.d("test", "gift record fail");
}
});
return view;
}
因为切换时会回调onConfigurationChanged()函数,因此需要在此函数中设置方向、对页面进行重绘:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int mCurrentOrientation = newConfig.orientation;
if ( mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT ){
layoutManager.setOrientation(OrientationHelper.VERTICAL);
}else {
layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
}
recyclerView.removeAllViews();
recyclerView.getAdapter().notifyDataSetChanged();
}