EditText编辑框实验

原创  灵思致远  2018-05-16


1. 实验内容简介

(1)EditText同TextView功能基本类似,它们之间的主要区别是EditText提供了可编辑的文本框。

EditText是用户与系统之间的文本输入接口,用户通过这个组件可以把数据传给Android系统,然后得到想要的数据。EditText提供了许多用于设置和控制文本框功能的方法。

通过以下方法对文本框进行设置,如下:

        setText("Look,I have  been changed!");//设置文本内容

        setTextColor(Color.rgb(0,255,0));//设置文本颜色

        setTextSize(20);//设置文本大小,以像素为单位

常用的属性如下:

Android:singleLine//是否单行或者多行,回车是离开文本框还是文本框增加新行

android:numeric //只接受数字

android:phoneNumber //输入电话号码

android:inputType设置文本的类型,用于帮助输入法显示合适的键盘类型

android:ems设置TextView的宽度为N个字符的宽度。这里测试为一个汉字字符宽度,如图:

android:maxEms设置TextView的宽度为最长为N个字符的宽度。与ems同时使用时覆盖ems选项。

android:minEms设置TextView的宽度为最短为N个字符的宽度。与ems同时使用时覆盖ems选项。

android:maxLength限制显示的文本长度,超出部分不显示。

android:lines设置文本的行数,设置两行就显示两行,即使第二行没有数据。

android:maxLines设置文本的最大显示行数,与width或者layout_width结合使用,超出部分自动换行,超出行数将不显示。

android:minLines设置文本的最小行数,与lines类似。

android:singleLine设置单行显示。如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。如android:text="test_ singleLine "android:singleLine="true"

android:text设置显示文本.

android:textSize设置文字大小,推荐度量单位”sp”,如”15sp”

(2)编辑框使用步骤:

步骤1:声明变量

步骤2:通过FindViewById关联或绑定

步骤3:监听用户输入动作

(3)使用TextWatcher监听EditText变化

a.文本改变前:beforeTextChanged

b.文本改变:onTextChanged

c.文本改变之后:afterTextChanged

(4)学会实现当用户在编辑框输入内容时,文本框同时显示用户输入,具体步骤如下。

2. UI界面布局


对应的大纲:


3. 代码编写和调试

MainActivity.java

public class MainActivity extends Activity {

    TextView mtv;

    EditText met;

    @Override

    protected void  onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mtv=(TextView)findViewById(R.id.textView1);

        met=(EditText)findViewById(R.id.editText1);

        met.setTextColor(Color.rgb(122,100, 25));

        met.setTextSize(15);

        met.addTextChangedListener(newTextWatcher() {

           

            @Override

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                Stringstr=met.getText().toString();

                mtv.setText(str);

               

            }

           

            @Override

            public void beforeTextChanged(CharSequence s, int start, int count,

                   intafter) {

                // TODOAuto-generated method stub

               

            }

           

            @Override

            public void afterTextChanged(Editable s) {

                // TODOAuto-generated method stub

               

            }

        });

    }

}



猜你喜欢

转载自blog.csdn.net/leansmall/article/details/80368860