起因
为了在普通布局中嵌入多个switchpreference,自然就使用了PreferenceFragment来加载preferencescreen来实现。
但是测试时发现,如果调大字体,就会造成布局高度超出一屏,而且无法滑动。
解决过程
首先想到的是在布局外加一层ScrollView,但是实际效果却是PreferenceFragment高度被压缩。查了一下发现PreferenceFragment里也有一个listview,类似Scrollview嵌套ListView的效果。
然后又是一通搜索,找到一个方法,需要重写PreferenceFragment的onActivityCreate()方法,自己计算listview的高度。
代码如下:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View rootView = getView();
ListView list = (ListView)rootView.findViewById(android.R.id.list);
list.setDivider(null);//去掉SwitchPreference之间的分割线
Adapter adapter = list.getAdapter();
if (adapter != null) {
int height = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View item = adapter.getView(i, null, list);
item.measure(0, 0);
height += item.getMeasuredHeight();
LinearLayout frame = (LinearLayout) getActivity().findViewById(R.id.privacy_fragment); //Modify thisfor your fragment
ViewGroup.LayoutParams param = frame.getLayoutParams();
param.height = height + (list.getDividerHeight() * adapter.getCount());
frame.setLayoutParams(param);
}
}
}
以上代码来自(PreferenceFragment放在ScrollView中高度为0 高度失效)
经过验证,发现效果很不好。
结果
困扰了三天后,突然想到,为什么不试试拆开preferencescreen呢?每一个fragment中只加入一个switchpreference,然后在布局中加入多个fragment。
经过验证,这种方案效果非常好。
当在ScrollView中使用PreferenceFragment展示多个switchpreference时,遇到字体增大导致布局超出屏幕且无法滚动的问题。尝试通过自定义listview高度未成功。最终解决方案是将preferencescreen拆分为多个单独的PreferenceFragment,每个包含一个switchpreference,布局中添加多个这样的fragment,实现完美适配。

1万+

被折叠的 条评论
为什么被折叠?



