EditText填充无法在Android中按预期方式工作

Har*_*iya 1 xml android android-layout android-edittext android-studio

我在MarshMallow设备上进行了测试。当我写了XML EditText和集PaddingBottomRetype EditText。但它不起作用。但是,当我设置PaddingLeftNew PassWord EditText工作正常。

方法:1

xml代码:

 <EditText
            android:id="@+id/change_password_old_password_edittext"
            android:layout_below="@+id/change_password_mobileNumber_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Old Password"
            android:layout_marginTop="20.0dip"
            android:textColorHint="#40000000"
            android:textSize="@dimen/textsize16"/>

        <EditText
            android:id="@+id/change_password_new_password_edittext"
            android:layout_below="@+id/change_password_old_password_edittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="New Password"
            android:layout_marginTop="20.0dip"
            android:textColorHint="#40000000"
            android:paddingLeft="10dip"
            android:textSize="@dimen/textsize16"/>

        <EditText
            android:id="@+id/change_password_retype_password_edittext"
            android:layout_below="@+id/change_password_new_password_edittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Retype Password"
            android:layout_marginTop="20.0dip"
            android:paddingBottom="10dip"
            android:textColorHint="#40000000"
            android:textSize="@dimen/textsize16"/>
Run Code Online (Sandbox Code Playgroud)

屏幕截图:

在此处输入图片说明

方式:2

然后,我决定以PaddingBottom编程方式进行设置。但是它给出了奇怪的输出。

Java代码:

内部OnCreate方法

   EditText change_password_retype_password_edittext = (EditText)findViewById(R.id.change_password_retype_password_edittext);
        change_password_retype_password_edittext.setPadding(0,0,0,10);
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

注: 我已经测试上MarshmallowLolliPopJellybean。但是在所有设备上都无法正常工作。

Jan*_*iya 5

您未指定填充的单位,因此pixel默认情况下会采用较小的填充单位,dp因此结果与您的预期不符。

将像素转换为dp,您将获得解决方案:

int paddingPixel = 10;
float density = getResources().getDisplayMetrics().density;
int paddingDp = (int)(paddingPixel * density);
change_password_retype_password_edittext.setPadding(0,0,0,paddingDp);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:以编程方式在视图上添加填充