文章目錄
最近在開發商城,主頁面這樣:
三層嵌套:rv+vp+gv,期間發現了不少問題,梳理如下:
一、gridView嵌套問題
(1)rv嵌套gv中,只顯示一行
無論設置match_parent 還是 wrap_content,都只顯示一行。解決方案:使用最大模式測量(最大父控件高度)
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
(2)grdivew 自動獲取焦點,滑動vp時,導致rv自動豎直滾動
解決:rv設置 descendantFocusability屬性。
blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點
二、ViewPager高度不固定問題
(1)ViewPager高度依賴於 子Fragmment高度,動態測量。
public class AutoHeightViewPager extends ViewPager {
private int current;
private int height = 0;
/**
* 保存position與對於的View
*/
private HashMap<Integer, View> childrenViews = new LinkedHashMap();
public AutoHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (childrenViews.size() > current) {
View child = childrenViews.get(current);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
//切換tab的時候重新設置viewpager的高度
public void resetHeight(int current) {
this.current = current;
if (childrenViews.size() > current) {
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
if (layoutParams == null) {
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
} else {
layoutParams.height = height;
}
setLayoutParams(layoutParams);
}
}
/**
* 保存position與對應的View
*/
public void setObjectForPosition(View view, int position) {
childrenViews.put(position, view);
}
(2)android 9.0上vp第一頁數據初始不展示(高度測量失敗)。
解決方案:在Fragment渲染完成,或rv渲染完成後,手動調用測量,重新繪製一遍。
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
if (tabPosition == 0) {
viewPager.resetHeight(0);
}
return false;
}
});