TextView和EditText『Android系列四』

来源:互联网 发布:男士包品牌 知乎 编辑:程序博客网 时间:2024/04/28 22:10

        路漫漫其修远兮,吾将上下而求索。


        这篇文章主要是谈谈两个标签:TextView和EditText。TextView相当于HTML中的label,EditText相当于HTML中的输入框。


        打开我们的好伙伴Eclipse,然后File--New--Android Application Project,新建工程FirstBase,这时候就可以直接在虚拟机中运行了,好吧,虽然只有干巴巴的几个字:hello world。


        可是,可是就没有人问,这几个字从哪里来的吗?还有,为什么不是hello kitty而是hello world呢?如果你在初次接触的时候有这个疑问,恭喜你,你有一个追根究底的好习惯。


        那么,这些显示的内容从哪里来?Search一下,你就知道——按下ctrl+H:



        下面的结果显示:



        打开这个strings.xml文件,在前面文章中已经说过,values这个文件夹里面都是些常数资源,打开以后会发现有这么一行代码:

    <string name="hello_world">Hello world!</string>

         有源头了,还得有渠道,怎么获取这个常数的值呢,从上面的代码看到,常数名称为"hello_world",继续search,结果在layout文件夹下面的main.xml中找到:

<RelativeLayout 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" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="@string/hello_world"        tools:context=".Main" /></RelativeLayout>

       
 前面提到过layout为版面配置目录,页面上显示的内容都在这里配置,这就很好解释了为什么页面上为什么显示了Hello world!


         问题又来了,这些个android:layout_*之类的是什么玩意儿?相信我,这不是罗嗦,这篇文章打字说出来又臭又长,在脑子里面也就是一闪念的事情,但搞清楚这个很有必要:

         android:layout_width为控件的宽度,有三个值:match_parent,fill_parent,wrap_content,前两个表达的意思都是填充满父容器,只不过match_parent是最新的写法,fill_parent是古老的写法不提倡,wrap_content为有多少文字长度,就有多长的控件,大概意思是这个,也别纠结我的话土气,能理解就好。

         android:layout_height都看出来了,height高度,控件的高度,也是有三个值,同上不解释。

         android:layout_centerHorizontal,就按英文意思来,水平居中,true or false,it‘s up to you!

         android:layout_centerVertical,垂直居中,true or false,it's up to you too.

         android:text="@string/hello_world",获取values文件夹下某个xml文件中节点为string的名为hello_world的常量值。


         继续学习EditText,直接在main.xml添加代码:


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

         最后一个android:inputType="number"是限定这个文本输入框只能录入数字,如果不写这句代码会有什么影响?在界面上没有任何影响,但是eclipse会给你一个黄灿灿的警告提示:This text field does not specify an inputType or a hint。


         好了,现在两个控件都添加上了,我们看看效果吧(去掉了TextView中的居中设置代码,为了发现问题):



        光标放上去,竟然会盖住Hello world!这是个问题,初次发现这个问题以后,就又添加了2个TextView控件,效果明显暴露出来了,他们竟然全部叠加到一起了!!!


        好吧,经过Search轻易发现了这是布局的问题,于是,我把main.xml文件中的标签RelativeLayout改为LinearLayout就OK了。后面的文章会涉及到这个问题。


原创粉丝点击