您可以通过以下方式在屏幕的左上角设置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()
方法,因此我不确定如何设置这些属性。 LinearLayout
位于RelativeLayout
。
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无法强制转换为android.widget.RelativeLayout $ LayoutParams
答案 0 :(得分:1)
该解决方案原来是使用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);
答案 1 :(得分:0)
这是它的工作方式,
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;
btnBar.setLayoutParams(params);