2025-02-09

一直想寫點東西,但不知道寫什麼,一直在學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的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *