在Android中以编程方式修复屏幕尺寸问题

时间:2017-01-23 14:32:47

标签: android android-layout android-linearlayout

我正在创建Android应用程序。这将动态创建问题。但基于移动屏幕尺寸视图不正确。我不知道如何解决这个问题。我附上了从不同手机拍摄的图像。 屏幕尺寸-3.7" ,屏幕尺寸-5.0"

wenzhixin/multiple-select enter image description here

所有元素大小都根据屏幕大小而变化。任何一个帮助在Android中显示响应式屏幕。

我的代码是:

lView.setBackgroundColor(Color.parseColor("#FFFFFF"));
lView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 220);
GradientDrawable gdtitle = new GradientDrawable();

gdtitle.setCornerRadius(5);
ImageView title = new ImageView(Main2Activity.this);
title.setImageResource(R.drawable.logo);
title.setLayoutParams(layoutParams2);
title.setBackgroundDrawable(gdtitle);
lView.setOrientation(LinearLayout.VERTICAL);
lView.addView(title);

GradientDrawable gd3 = new GradientDrawable();
gd3.setCornerRadius(30);
gd3.setColor(Color.parseColor("#003366"));
gd3.setStroke(0, 0xFF000000);

TextView uname1 = new TextView(Main2Activity.this);
uname1.setText("Hello , "+Sessionname);
uname1.setGravity(Gravity.LEFT);
uname1.setTextColor(Color.parseColor("#003366"));
uname1.setTextSize(20);
uname1.setLayoutParams(l2);

et1 = new TextView(Main2Activity.this);
et1.setHeight(100);
et1.setTextColor(Color.WHITE);
et1.setHintTextColor(Color.WHITE);
et1.setGravity(Gravity.CENTER);
et1.setHint("Select Date");
et1.setBackgroundDrawable(gd3);
et1.setTextSize(15);
et1.setLayoutParams(l2);

lView.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout.LayoutParams l4 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
l4.gravity=Gravity.CENTER;
lHorizontalView1.setOrientation(LinearLayout.HORIZONTAL);
lHorizontalView1.setLayoutParams(l4);
lHorizontalView1.addView(uname1);
lHorizontalView1.addView(et1);
lView.addView(lHorizontalView1);

1 个答案:

答案 0 :(得分:1)

您正在以像素为单位对您的值进行硬编码。例如,对于您的身高,您拨打setHeight(100)即表示将此View设置为100px高。但是,不同的屏幕密度看起来会完全不同。给定一个固定的屏幕尺寸(例如5英寸),一个设备的分辨率可能为480x800而另一个设备的分辨率可能为1440x2560,您100px的设置将完全与您现在拥有的设置相同。

使用Display Metrics来检索屏幕密度,并使用device independent pixelsdipdp)而不是像素(px)作为单位。例如,您可以根据设备的密度设置高度,如下所示:

setHeight(100 * getResources().getDisplayMetrics().density);

但是,您所需的高度可能必须更小,因为它将变为100dp,因此您可能需要将其设置为50之类。四处游戏,直到获得理想的结果。

然后您的View在各设备上看起来都是统一的。