说一下遇到的问题,项目里需要一个类似支付时需要的密码输入框,需要输入英文数字和符号。网上很多的,可是都有一点小毛病,比如手动切换了输入键盘,输入一个密码后键盘自动切换回去了,源代代码比较多,也有点复杂,修改起来太麻烦了。所以自己写个简单点的。先看看效果。
输入中文了,不过没关系,只需要修改EditText的inputType就可了,如下
<EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@null" android:cursorVisible="false" android:inputType="textPassword" android:textColor="#ffffff" android:visibility="visible" />
是不是很简单呢,和普通控件没啥区别。这是输入框,用来接收输入的内容,还需要几个TextView,用来显示输入的密码,textview是放在一个layout里面的,所以需要放一个layout,如下
<EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@null" android:cursorVisible="false" android:inputType="textPassword" android:textColor="#ffffff" android:visibility="visible" /> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="match_parent" android:autofillHints="fsadf" android:background="@drawable/shape_stroke" android:orientation="horizontal" />
把这两放在一起,让他们重叠起来,在把EditText的字体设置成背景,完美。。。。。
接下来定义一个类,继承RelativeLayout,在把刚才的xml文件添加进去,然后给xml文件里的layout动态添加几个textview,用来显示密码或小黑点,就解决问题了,如下
int index = 0; while (index < mPasswordLength) { View dividerView = new View(context); LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams((int) dip2px (context, 2), LinearLayout.LayoutParams.MATCH_PARENT); dividerView.setBackgroundColor(ContextCompat.getColor(context, R.color .w3)); ll.addView(dividerView, dividerParams); TextView textView = new TextView(context); textView.setTextSize(20); textView.setTextColor(Color.BLACK); textView.setGravity(Gravity.CENTER); textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f); ll.addView(textView, textViewParams); tv[index] = textView; index++; }
可以说的代码就这么多,是不是太简单了点!!!要的就是这个效果,思路差不多就这样,不太明白的可以下载demo,一看就明白的,接下来就是修改成自己项目里的要求的样子了。