PreferenceFragment放在ScrollView中高度爲0 高度失效

PreferenceFragment自帶滑動屬性,當內部的每一個ListPreferenceg高度爲wrapcontent時,嵌套進可滑動的layout中,高度無法明確計算。

爲什麼?

view什麼時候計算高度?

 

解決方案:

在繪製前手動計算高度

 

來源:https://stackoverflow.com/questions/22973089/scrollview-linearlayout-preferencefragment-is-zero-height/36013219#36013219

 

The question is quite old but in case someone else stumbles upon this, I've managed to find a solution. Just like @Ewoks mentioned, I had to settle for a fixed height as well (which didn't always play well with varying dpi of the devices).

But with the help of this code I managed to make the height dynamic, which wraps the content nicely.

In your PreferenceFragment class do as follows:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getView() != null) {

        ListView listView = (ListView) getView().findViewById(android.R.id.list);
        Adapter adapter = listView.getAdapter();

        if (adapter != null) {
            int height = 0;
            //int height = listView.getPaddingTop() + listView.getPaddingBottom();

            for (int i = 0; i < adapter.getCount(); i++) {
                View item = adapter.getView(i, null, listView);

                item.measure(0, 0);
                height += item.getMeasuredHeight();
            }

            FrameLayout frame = (FrameLayout) getActivity().findViewById(R.id.content_frame); //Modify this for your fragment

            ViewGroup.LayoutParams param = frame.getLayoutParams();
            param.height = height + (listView.getDividerHeight() * adapter.getCount());
            frame.setLayoutParams(param);
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章