当前位置:操作系统 > 安卓/Android >>

Android[初级教程]第一篇 Button控件和TextView控件

一直想写点东西,但不知道写什么,一直在学Android开发,正好借此机会练练写作,呵呵,长话短说,今天学习Android的Button控件和TextView控件,什么??你还不会建立Android开发平台?那麻烦您去百度或是Google一下吧.

Button控件有事件监听,如果想处理单击事件的话,就需要为Button控件注册监听器,好了,我们来看一下今天的代码,首先是main.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/text" android:layout_width="fill_parent" 
        android:layout_height="wrap_content" android:text="@string/hello" /> 
    <Button  android:layout_width="match_parent" 
        android:layout_height="wrap_content" android:text="按钮" android:id="@+id/button"></Button> 
</LinearLayout> 

这里面多加了一个Button控件,并为它设置了一个id(android:id="@+id/button").什么?为什么要设置ID?那是为了在Activity中方便找到main.xml中的控件,并对相应的控件建立事件或处理.你可不想点击控件的时候什么反正都没有吧?好了,我们再看一下Activity中的代码吧:

 
import java.util.Date; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
 
public class ButtonDemoActivity extends Activity implements OnClickListener 

    private TextView text = null; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
 
        // 通过ID查找到main.xml中的TextView控件 
        text = (TextView) findViewById(R.id.text); 
 
        // 通过ID查找到main.xml中的Button控件 
        Button button = (Button) findViewById(R.id.button); 
        // 为Button控件增加单击监听器 
        button.setOnClickListener(this); 
 
    } 
 
    /**
     * 对main.xml中所有控件进行单击监听,当然您必须要对控件进行监听注册 例:button.setOnClickListener(this);
     */ 
    @Override 
    public void onClick(View v) 
    { 
        updateTime(); 
 
    } 
 
    private void updateTime() 
    { 
        //设置text控件中的文本 
        text.setText(new Date().toString()); 
 
    } 

OK,代码写完了,那我们就让模拟器来运行一下,单击每一次按钮,看一下上面的TextView是不是有变化?很简单吧?从今天开始,我们就正式的来学习Android的开发了.

摘自:kangkangz4的专栏

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,