如何根据屏幕高度设置视图的高度?
<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
您可以获取LayoutParams对象视图,然后将高度和宽度设置为动态查看,如下面的代码:
View view = (View)findViewById(R.id. myRectangleView);
LayoutParms layoutParams = view.getLayoutParms();
layoutParms.height = 200;
layoutParms.width = 300;
你可以用这个:
public static int getScreenHeightInDP(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;
return Math.round(screenHeightInDP);
}
我在我的尝试过这个解决方案。希望对你好。
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;
}
}
}