我正在开发一个应用程序,它以编程方式将EditText框插入到布局中。当我以编程方式添加EditText时,我似乎无法使中心文本工作,但是当我通过XML布局执行它时它工作正常。当我添加后台资源时,我已经确定了问题。我在下面添加了代码,通过代码和XML添加EditText。
<LinearLayout
android:id="@+id/layoutLinear_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background" >
<LinearLayout
android:id="@+id/layoutLinear_answerDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:gravity="center"
android:background="@drawable/background_field"
android:layout_gravity="center"
android:layout_marginLeft="120dp"
android:layout_marginRight="120dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
android:hint="F"
android:text="F" />
</LinearLayout></LinearLayout>
然后在主代码中。我以编程方式添加EditText。我已经删除了边距和填充,只是为了清楚地识别问题。
LinearLayout layoutLinear_answerDisplay = ((LinearLayout) this.findViewById(R.id.layoutLinear_answerDisplay));
EditText ed = new EditText(this);
ed.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
ed.setLayoutParams(layoutParams);
ed.setBackgroundResource(R.drawable.background_field);
ed.setTextSize(30);
ed.setHint("F");
ed.setText("F");
layoutLinear_answerDisplay.addView(ed);
以下是ouptut。您可以从图像中看到顶部EditText具有居中文本(这是通过XML代码完成的)。您可以从底部的EditText中看到文本偏离中心(通过后面的代码完成)。
我还附加了EditText的后台资源。任何帮助将不胜感激。感谢
答案 0 :(得分:0)
看起来您正在使用layout_margin(左和右)来居中xml edittext。当你在代码中设置它们时,你没有考虑到dp缩放。
final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 120.0, getResources().getDisplayMetrics());
使用类似上面的内容将120度量缩放到正确的像素等效值,然后它们将在同一个位置。但也要意识到,您不需要为左/右边距使用如此高的值来使文本居中