編輯:Android開發教程
Android中Button控件應該算作是比較簡單的控件,然而,它的使用頻率卻是非常的高,今天,我在這裡總 結了三種常用的點擊Button實現其功能的方法。
1.很多時候,我們在用到Button控件時,往往都是“ 一次性”使用,這時,為了方便起見,我們一般采用的是匿名內部類的方法,形如這樣:
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("您點擊了Button1");
}
});
我們可以看到,這樣的代碼不僅簡短,而且清晰易懂,不過,這樣的方法一般只是適用 於這個Button使用的次數不多或是“一次性”使用
2.當Button有多個或者Button的使用次數很多時, 我們需要采用綁定監聽器的做法,其實,綁定監聽器也有幾種方法,不過,我在這裡就不一一列舉了,畢竟那 些方法在實際的應用中也不常見。
我們一般的方法是實現OnClickListener接口,並實現其中的方法, 正如這樣:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button2:
System.out.println("您點擊了Button2");
break;
default:
break;
}
}
注:onClick方法是OnClickListen接口中的方法,我們實現這個接口就必須實現它的方法。
3.這是一種最為簡單的方法,我們需要做的就是添加一個方法並為Button添加一個屬性:
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3 測試"
android:onClick="clickHandler"
/>
其中,我們比平時多添加了onClick屬性。
那麼,我們需要在代碼中添加我 們在屬性中聲明的方法:
public void clickHandler(View view) {
System.out.println("您點擊了Button3");
}
最後,貼出完整的源代碼和實現效果截圖:
1.布局文件
<LinearLayout
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"
tools:context=".MainActivity"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1 測試"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2 測試"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3 測試"
android:onClick="clickHandler"
/>
</LinearLayout>
Android開發入門(二)使用意圖 2.5 使用Intent調用內置應用程序
我們已經了解了如何在自己的單個應用中調用activity。但是,android開發中比較重要的一點,就是使 用intent調用其他應用的activity。特別地,你的應用
Android粉絲眼中iOS 7與Android 4.2功能對比
蘋果WWDC大會結束後,著名Android論壇Droid-life發布了iOS 7與Android4.2操作系統功能對比的文章,作者作為Android 粉絲,稱谷歌早已懶
Android LibGDX游戲引擎開發教程(八) 中文字體的顯示和繪制(下)
在上一篇的文章中,我們介紹了Hiero這個非常好用工具的使用,但是LIbgdx的BitmapFont不支持多圖,常 用漢字3500個,你總不能用hiero自己做吧,那怎麼
Android ApiDemos示例解析(2) SimpleAdapter,ListActivity,PackageManager
創建好ApiDemo項目後,就可以逐個示例的來分析代碼,這裡假定讀者已對Android開發有些了解或是讀過Android簡明開發教 程。首先是看ApiDemo的主Acti