私のフラグメントの中では、次のようにGridLayoutを設定しています。
mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));
とします。
そこで、ユーザーが携帯電話やタブレットを回転させたときに、この 2
を 4
に変えたいだけなんです。onConfigurationChanged`` を読んで、それを私のケースで動作させようとしましたが、正しい方法で動作していません。携帯電話を回転させると、アプリがクラッシュしてしまいます...。
この問題を解決する方法を教えてください。
以下は、正しく動作していない私の解決策を見つけるためのアプローチです。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}
}
ありがとうございました。
もし、複数の条件があったり、複数の場所で値を使用したりすると、すぐに手に負えなくなる可能性があります。以下のような構造を作ることをお勧めします。
res
- values
- dimens.xml
- values-land
- dimens.xml
で、res/values/dimens.xml
があります。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="gallery_columns">2</integer>
</resources>
とres/values-land/dimens.xml
があります。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="gallery_columns">4</integer>
</resources>
そして、コードは次のようになる(そして永遠に残る)。
final int columns = getResources().getInteger(R.integer.gallery_columns);
mRecycler.setLayoutManager(new GridLayoutManager(mContext, columns));
例えば、-land
の代わりに -w500dp
/-w600dp
/-w700dp
リソースフォルダを使用するなど、列数を決定する新しい方法を簡単に追加できることがお分かりいただけると思います。
また、これらのフォルダを別のリソースフォルダとしてグループ化することも簡単です。
android {
sourceSets.main.res.srcDir 'src/main/res-overrides' // add alongside src/main/res
}
この処理はonCreateViewメソッド内で行うようにしてください。
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
}
else{
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}