是否将"物料持久底部板材"的高度设置为屏幕高度的一半



所以我在Coordinator Layout中创建了一个持久的底部工作表。我可以将LinearLayout的高度设置为某个值500dp,但我想实现的是将其高度设置为屏幕的一半。我想我必须通过DisplayMetrics获得屏幕高度,并以某种方式将其应用于LinearLayout


<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".post.PostActivity">
<LinearLayout
android:id="@+id/gallery_bottom_sheet"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_marginHorizontal="@dimen/margin_very_small"
android:background="@drawable/background_sheet"
android:orientation="vertical"
app:behavior_peekHeight="@dimen/peek_height"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<View
android:layout_width="@dimen/width_forty"
android:layout_height="@dimen/divider_large"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/margin_small"
android:layout_marginBottom="@dimen/margin_small"
android:background="?android:listDivider" />
<GridView
android:id="@+id/gallery_grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="@dimen/grid_spacing"
android:nestedScrollingEnabled="true"
android:numColumns="4"
android:verticalSpacing="@dimen/grid_spacing" />
</LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

首先通过DisplayMetrics计算出所需的屏幕高度

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int halfScreenHeight = displayMetrics.heightPixels / 2;

然后得到现有linearLayoutgetLayoutParams()。设置高度并应用。(也铸造成CoordinatorLayout.LayoutParams(

LinearLayout linearLayout = findViewById(R.id.gallery_bottom_sheet);
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) linearLayout.getLayoutParams();
params.height = halfScreenHeight;
linearLayout.setLayoutParams(params);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
LinearLayout linearLayout = findViewById(R.id.gallery_bottom_sheet);
LayoutParams params = layout.getLayoutParams();
params.height = (int) displayMetrics.heightPixels/2;
linearLayout.setLayoutParams(params);

只需将上面的代码复制粘贴到"onCreate"方法中的java文件中。

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int requiredHeight = height/2;
LinearLayout linearLayout = findViewById(R.id.gallery_bottom_sheet);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, requiredHeight);
linearLayout.setLayoutParams(layoutParams);

只需将上面的代码复制粘贴到您的java文件中即可。

相关内容

  • 没有找到相关文章

最新更新