ViewGroup.LayoutParams params = recyclerView.getLayoutParams(); ViewGroup.MarginLayoutParams marginParams = null; //获取view的margin设置参数if (params instanceof ViewGroup.MarginLayoutParams) {marginParams = (ViewGroup.MarginLayoutParams) params;} else { //不存在时创建一个新的参数 //基于View本身原有的布局参数对象 marginParams = new ViewGroup.MarginLayoutParams(params);} marginParams.setMargins(0,0,1,0);
千万记住这里面的if 语句的判断, 如果直接marginParams = new ViewGroup.MarginLayoutParams(params); 会报错
E/AndroidRuntime: FATAL EXCEPTION: mainProcess: kodulf.swiperefreshlayoutrecyclerviewdemo, PID: 14673java.lang.ClassCastException: android.view.ViewGroup$MarginLayoutParams cannot be cast to android.widget.LinearLayout$LayoutParamsat android.widget.LinearLayout.measureVertical(LinearLayout.java:779)at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)at android.view.View.measure(View.java