通过上一篇文章,知道了如何创建一个应用程序来显示一个静态的View。然而,在大多数情况下仅仅显示是不够的,应该还需要与用户的交互行为。现在完成一个简单的和用户交互的示例。
这个小程序的需求是:
画面上有三行元素:
第一行是一个TextView,用来显示文字
第二行是一个EditText,用户将在此输入文字
第三行是一个Button
用户点击Button之后,会在第一行的TextView中显示:Hello,(用户在第二行中输入的文字)。
比如说用户在输入框中输入:“Roiding.com”,那么点击Button之后,会在显示区域显示:“Hello, Roiding.com”。
要完成这个程序,大概需要用5步:
第1步,先完成UI的设计,在res/layout/目录下创建一个文件,名为:sayhello.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textview_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20px"
android:textStyle="bold"
/>
<EditText
android:id="@+id/edittext_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button_sayhello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sayhello"
/>
</LinearLayout>
如果已经看过前一篇文章的话,这个文件还是比较容易懂的,不需要太多的解释了,只解释一下这几个语句:
android:id=”@+id/textview_display”
这个是用来为当前的View声明一个ID,这样,在Java程序中就可以通过这个ID来找到这个元素,进而能够操作这个元素。
android:textSize=”20px”
声明字体大小为20px,对于每种View,都会有一系列的可以设置的属性,具体的需要参考每个View的说明文档。
第2步,创建好这个布局文件之后,再把这个文件需要的android:text=”@string/sayhello”在res/values/strings.xml中声明一下:
<string name="sayhello">say hello</string>
第3步,现在,UI已经设计好了,那么创建一个Activity(命名为:SayHello.java)来显示这个UI:
package com.roiding.study;
import android.app.Activity;
import android.os.Bundle;
public class SayHello extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sayhello);
}
}
在这一步完成的时候,就可以运行一下这个Activity,看看最终显示的效果是否和预期的一致,如果有差别,再调整一下。
第4步,为UI添加交互动作,添加完毕之后的SayHello.java:
package com.roiding.study;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SayHello extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sayhello);
Button btn = (Button) findViewById(R.id.button_sayhello);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText edt = (EditText) findViewById(R.id.edittext_name);
TextView tv = (TextView) findViewById(R.id.textview_display);
tv.setText("Hello," [...]
Recent Comments