Android應用開發基礎篇(1)—–Button

來源:互聯網
上載者:User

一、概述

       Button,顧名思義就是按鈕的意思,它主要的功能是響應使用者按下按鈕時的動作。

二、應用

     建立一個工程,名字為MyButton,在/res/layout/main.xml檔案中添加以下內容:

1 <Button
2 android:id="@+id/button"
3 android:layout_width="fill_parent"
4 android:layout_height="wrap_content"
5 android:text="Click"
6 />

添加後main.xml檔案的內容為:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <TextView
8 android:layout_width="fill_parent"
9 android:layout_height="wrap_content"
10 android:text="@string/hello" />
11
12 <Button
13 android:id="@+id/button"
14 android:layout_width="fill_parent"
15 android:layout_height="wrap_content"
16 android:text="Click"
17 />
18
19 </LinearLayout>

接著修改MyButtonActivity.java檔案,在MyButtonActivity類裡聲明一個Button對象mButton

 

private Button mButton = null;

在onCreate()函數裡通過findViewById()函數執行個體化mButton

 

mButton = (Button)findViewById(R.id.button);

緊接著編寫mButton的監聽函數

 

mButton.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
PlayToast("You Clicked Button");
}
});

其中PlayToast()函數是通過Toast類用來顯示"You Clicked Button"這串字串的,比較簡單,如下所示:

private void PlayToast(String s)
{
Toast toast = Toast.makeText(this, s , Toast.LENGTH_LONG);
toast.show();
}

好了。下面是MyButtonActivity.java檔案的完整內容:

 1 package com.nan.button;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.widget.Button;
7 import android.widget.Toast;
8
9
10
11 public class MyButtonActivity extends Activity
12 {
13 private Button mButton = null;
14
15
16 /** Called when the activity is first created. */
17 @Override
18 public void onCreate(Bundle savedInstanceState)
19 {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.main);
22
23 mButton = (Button)findViewById(R.id.button);
24 mButton.setOnClickListener(new View.OnClickListener()
25 {
26
27 @Override
28 public void onClick(View v)
29 {
30 // TODO Auto-generated method stub
31 PlayToast("You Clicked Button");
32 }
33 });
34
35 }
36
37
38 private void PlayToast(String s)
39 {
40 Toast toast = Toast.makeText(this, s , Toast.LENGTH_LONG);
41 toast.show();
42 }
43
44 }

運行程式,並點擊按鈕,效果如下:

 


 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.