如何优雅地用LayoutParams动态改变view的大小

1,093 阅读1分钟
xml布局:
<RelativeLayout        
   android:id="@+id/frame"        
   android:layout_width="match_parent"        
   android:layout_height="match_parent"        
   android:background="#00000000" >        
  <SurfaceView            
       android:id="@+id/video_surface"            
       android:layout_width="match_parent"           
       android:layout_height="match_parent"/>    
</RelativeLayout>

代码:

RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(1920,1080);
videoSurface.setLayoutParams(layoutParams);
代码分析:
这里我们要知道我们要改变大小的view在什么布局里面(LinearLayout,Relativelayout,...),然后new 相应的layoutParams。
这里我们的SurfaceView在RelativeLayout里面,所以要new RelativeLayout.LayoutParams;
我们可以传入/修改不同的宽高参数来控制view的大小。

优化(重点)

不得不说上边的过程还是很麻烦的,当LayoutParams类型不对时程序分分钟抛出异常,而且每次都要去布局里面找相应的父布局,然后才能生成相应的LayoutParams对象。

优化方法:使用反射生成view相对应的LayoutParams对象。

我们查看相关文档可以知道所有view的LayoutParams都是ViewGroup.LayoutParams的子类。

反射LayoutParams代码:

Class<? extends ViewGroup.LayoutParams> LayoutParamsClass=videoSurface.getLayoutParams().getClass();

videoSurface.setLayoutParams( LayoutParamsClass.getDeclaredConstructor(int.class,int.class).newInstance(720,720));

分析:

videoSurface.getLayoutParams().getClass()拿到类名,getDeclaredConstructor调用其有参数的构造方法,newInstance来生成对象

这样我们就用反射绕过了实例化 LayoutParams时可能出现的与父view的LayoutParams不一致的问题。