我们可以从editText的中心开始游标而不使用重力

时间:2017-03-07 10:41:46

标签: android xml

我有一个布局我正在使用EditText我想从提示中心开始光标,但我不能使用引力属性,因为之前我遇到一个问题,当我点击edittext键盘覆盖该字段。因此,在删除重力属性后它工作正常。但现在我正面临这个问题。

 <RelativeLayout
                        android:layout_width="@dimen/dp_267"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginTop="@dimen/dp_25">

                        <EditText
                            android:id="@+id/et_name"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignParentTop="true"
                            android:layout_centerInParent="true"
                            android:background="@null"                                          android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789  ^*_,.-"
                            android:ellipsize="start"
                            android:hint="Name"
                            android:text=""
                            android:textAlignment="center"
                            android:maxLength="50"
                            android:paddingTop="@dimen/dp_10"
                            android:singleLine="true"                                android:textColor="@color/login_screen_default_color"
                            android:textColorHint="@color/Grey"
                            android:textCursorDrawable="@null"
                            android:textSize="18sp"
                            />

                    </RelativeLayout>

2 个答案:

答案 0 :(得分:0)

将重力设置为居中,并在onCreate()中添加以下内容:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

如果唯一的问题是您的EditText在点击它时被隐藏,那么上面的行将在键盘出现时向上移动您的布局。

答案 1 :(得分:0)

我制作了一种方法,用于设置中心提示的重力以及当焦点重力设置在左上方时

   private void setGravity(final EditText editText) {
    editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0) {
                // position the text type in the left top corner
                editText.setGravity(Gravity.LEFT | Gravity.TOP);

            } else {
                // no text entered. Center the hint text.
                editText.setGravity(Gravity.CENTER);

            }
        }
    });
}

对于键盘问题你可以设置android:windowSoftInputMode =&#34; adjustResize&#34;在manifest.xml文件中,将所有字段放在scrollview中。

 <ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    add your widgets here .......
</RelativeLayout>
 </ScrollView>