Android之EditText控件学习


什么是EditText

EditText是输入文本的组件
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"/>
</LinearLayout>

效果如下

Android之EditText控件学习_第1张图片


限制输入字符数量

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:maxLength="3"/>

限制输入字符为3,所以最多只能输入三个,再输入就无效果了


多行文本框

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:singleLine="false"/>
singleLine设置为true是就只能在一行显示,否则当超过一定长度就自动换行



限制EditText输入信息

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:inputType="number"/>

这里限制了输入类型为数值,所以输入其他文字无效


inputType输入类型有多种,我们可以根据需要选择不同的限制

Android之EditText控件学习_第2张图片


设置提示信息

    <EditText
        android:hint="我是EditText"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"/>

提示信息就是当我们没有任何输入时显示出来的信息,一旦我们进行了输入操作,提示信息就会消失


在EditText中显示图片

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	android:drawableLeft="@drawable/title"/>


设置圆角

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
	android:background="@drawable/shape"/>
所关联文件为shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:shape="rectangle">
	<!-- 填充的颜色 -->
	<solid android:color="#FFFFFF" />
	<!-- 设置矩形的四个角为弧形 -->
	<!-- android:radius 弧形的半径 -->
	<corners android:radius="7dip" />
</shape> 

观察发现,输入框已经不是直角矩形而是变成了圆角了


使用图片设置效果

    <EditText
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
	android:background="@drawable/editbox"/>
所关联文件为editbox.xml,在这个文件中,同时又关联了图片
<?xml version="1.0" encoding="UTF-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"  android:drawable="@drawable/edit_pressed" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/edit_pressed" />
    <item android:state_focused="false" android:drawable="@drawable/edit_normal" />
</selector>
在这里,我们使用了图片资源
当控件没有选中时

当控件选中时


总效果如图

Android之EditText控件学习_第3张图片



好了,关于EditText控件就学习到这里了。


你可能感兴趣的:(android,EditText)