After the initialization of Android View is completed, if you call measure and then set the click event, the click event will be invalid.

For example, for LinearLayout or RecyclerView, after the initialization is completed and the data is loaded, we call measure again to calculate the height and then setLayoutParams will invalidate the click event set later.

for example:

        RecyclerView rv_select =dialog.findViewById(R.id.rv_select); 

        //点击事件
        rv_select.setOnItemClickListener(new PopupAdapter.OnItemClickListener() {
    
    
         //....
        });

        // 重新测量一下rv_select的真实高度并限定最大值,注意!measure方法必须放在设置点击事件之后,否则点击事件会失效
        ViewGroup.LayoutParams params = rv_select.getLayoutParams();
        rv_select.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.height = Math.min(rv_select.getMeasuredHeight(), Tools.dp2px(mContext,290));
        rv_select.setLayoutParams(params);
Solution:

Calling the measure method after the RecyclerView is initialized may cause the item click event to fail because the measure method will re-measure and lay out the sub-item views of the RecyclerView, which may destroy the click listener that has been set.

To resolve this issue, try one of the following two solutions:

  1. Set the click listener before calling the measure method: Place the code for setting the click listener after the initialization of the RecyclerView is completed and before calling the measure method. This way, the click listener will still work after the measure method is called.

Sample code:

   // RecyclerView初始化
    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    // 设置点击监听器
    recyclerView.setOnItemClickListener(new OnItemClickListener() {
    
    
        @Override
        public void onItemClick(View view, int position) {
    
    
            // 处理点击事件
        }
    });

    // 调用measure方法
    recyclerView.measure(widthMeasureSpec, heightMeasureSpec);

2. Avoid calling the measure method again after the initialization is complete: If there is no need to call the measure method again, please make sure to call the measure method only once during the initialization phase. If layout updates are required, consider using other methods such as requestLayout() or invalidate().

Guess you like

Origin blog.csdn.net/wh445306/article/details/132024354