[英]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()
方法,因此我不確定如何設置這些屬性。 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
該解決方案原來是使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.