在 Android 上以编程方式设置视图的高度

如何根据屏幕高度设置视图的高度?


<View

    android:id="@+id/myRectangleView"

    android:layout_width="200dp"

    android:layout_height="50dp" //view height

    android:background="@drawable/rectangle"/>

目前高度设置为 50dp。我需要如下设置视图的高度:


View Height     Screen Size 

32 dp           ≤ 400 dp

50 dp           > 400 dp and ≤ 720 dp

90 dp           > 720 dp


守着星空守着你
浏览 193回答 3
3回答

小怪兽爱吃肉

您可以获取 View 的 LayoutParams 对象,然后设置 Height 和 Width 以动态查看,如下面的代码:View view = (View)findViewById(R.id. myRectangleView);LayoutParms layoutParams = view.getLayoutParms();layoutParms.height = 200;layoutParms.width&nbsp; = 300;

PIPIONE

我已经在我的身上尝试过这个解决方案。希望它对你没问题。import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.DisplayMetrics;import android.view.Display;import android.view.View;import android.view.ViewGroup;public class MainActivity extends AppCompatActivity {&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_main);&nbsp; &nbsp; &nbsp; &nbsp; View view = (View) findViewById(R.id.myRectangleView);&nbsp; &nbsp; &nbsp; &nbsp; ViewGroup.LayoutParams layoutParams = view.getLayoutParams();&nbsp; &nbsp; &nbsp; &nbsp; layoutParams.height = 500;&nbsp; &nbsp; &nbsp; &nbsp; Display display = getWindowManager().getDefaultDisplay();&nbsp; &nbsp; &nbsp; &nbsp; DisplayMetrics outMetrics = new DisplayMetrics();&nbsp; &nbsp; &nbsp; &nbsp; display.getMetrics(outMetrics);&nbsp; &nbsp; &nbsp; &nbsp; float density = getResources().getDisplayMetrics().density;&nbsp; &nbsp; &nbsp; &nbsp; float dpHeight = outMetrics.heightPixels / density;&nbsp; &nbsp; &nbsp; &nbsp; if ((int) dpHeight <= 400) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; layoutParams.height = 32;&nbsp; &nbsp; &nbsp; &nbsp; } else if ((int) dpHeight > 400 && dpHeight <= 720) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; layoutParams.height = 50;&nbsp; &nbsp; &nbsp; &nbsp; } else if ((int) dpHeight > 720) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; layoutParams.height = 90;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

慕森王

你可以使用这个:public static int getScreenHeightInDP(Context context) {&nbsp; &nbsp; DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();&nbsp; &nbsp; float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;&nbsp; &nbsp; return Math.round(screenHeightInDP);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java