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

时间:2019-02-16 07:49:25

标签: java android layout height

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

<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

3 个答案:

答案 0 :(得分:1)

您可以获取View的LayoutParams对象,然后将Height和Width设置为动态查看,如以下代码所示:

View view = (View)findViewById(R.id. myRectangleView);
LayoutParms layoutParams = view.getLayoutParms();
layoutParms.height = 200;
layoutParms.width  = 300;

答案 1 :(得分:0)

您可以使用此:

public static int getScreenHeightInDP(Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

    float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;

    return Math.round(screenHeightInDP);
}

答案 2 :(得分:0)

我在我的产品中尝试过此解决方案。希望对您有帮助。

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 {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View view = (View) findViewById(R.id.myRectangleView);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height = 500;

        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float density = getResources().getDisplayMetrics().density;
        float dpHeight = outMetrics.heightPixels / density;

        if ((int) dpHeight <= 400) {
            layoutParams.height = 32;
        } else if ((int) dpHeight > 400 && dpHeight <= 720) {
            layoutParams.height = 50;
        } else if ((int) dpHeight > 720) {
            layoutParams.height = 90;
        }
    }
}