如何以编程方式将布局设置为顶部和屏幕开始?

How to programmatically set Layout to Top and Start of screen?

您可以通过这样做将 LinearLayout 设置到屏幕的左上角:

  android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"

我想知道如何以编程方式执行此操作?

我有如下一段代码:

 LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    LinearLayout.LayoutParams btnBarParams = new LinearLayout.LayoutParams(screenWidth,screenHeight / 3);
 //Not sure how to set the layout to the top left.

但是在 LayoutParameters 中没有 addRule() 方法,所以我不确定如何设置这些属性。 LinearLayoutRelativeLayout.

编辑:我想我明白了,但我遇到了一个例外。这是我的解决方案:

   LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    LinearLayout.LayoutParams btnBarParams = new LinearLayout.LayoutParams(screenWidth,screenHeight / 3);
    btnBarParams.gravity = Gravity.START;
    btnBar.setLayoutParams(btnBarParams);

但我看不到这是否有效,因为我在解决方案的最后一行遇到异常

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

解决方案原来是使用RelativeLayout.LayoutParams

 LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    RelativeLayout.LayoutParams btnBarParams = new RelativeLayout.LayoutParams(screenWidth,screenHeight / 3);
    btnBarParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    btnBarParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    btnBar.setLayoutParams(btnBarParams);

这就是它的工作方式,

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

btnBar.setLayoutParams(params);