2013年7月6日 星期六

android Button元件

Android最基礎,最常用的就是Button元件,所以先教簡單的基本應用
先建立一個主程式Button1.java 和 layout面板 button1.xml (檔案名稱自訂)

先做版面的排版和元件
button1.xml layout版面
這邊可以做 Button元件的修改
background 後面是顏色的編碼。

button1.xml 程式碼
這邊出現黃色虛線不會造成執行影響,是因為名稱是直接輸入的,而不是經由R檔那邊連結的,它會判定不太合邏輯。


Button的主程式碼

函數庫的宣告
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

重點解說 :
1. Button bt1=(Button) findViewById(R.id.button1); 
// Button bt1 建立區域變數bt1,屬性Button。
// findViewById(int)到版面的資源去找介面元件的索引ID,R.id.button1--->是屬於整數int。

2. bt1.setOnClickListener(new mylistener()); 
// bt1.setOnClickListener() 對bt1設定一個OnClickListener函數點擊事件
// new mylistener() 建立新的函數,函數名稱自訂。
*  這邊建立Button的點擊事件是採用 implements 介面實做的方式,也是有其他的方式,但這邊就不多錯介紹了。

3. public class mylistener implements OnClickListener
// 對剛剛建立的新函數 mylistener() 去實做 OnClickListener介面
// 注意要在 public class Button1 extends Activity{} 裡面

Tip : 小技巧
 public class mylistener implements OnClickListener{}
//當你打完之後,mylistener底下會乘現紅色虛線,這時可以把滑鼠移過去,
此時會出現下圖

這時可以移進去點 Add unimplemented methods
就會幫你加上 public void onClick(View v) {}的函數了

4. Toast.makeText(Button1.this, "123", Toast.LENGTH_LONG).show();
// 這個Toast很常用,這邊可以做一些訊息提示,也可以用來偵錯。

Tip : 重點
Button1.this 這邊也可以寫作2種
(1) this (需要在本文內 OnCreate()函數內)
(2) getApplicationContext()(在本文以外的地方 離開OnCreate()函數時使用,本文內也可以)
不過用 Button1.this(檔名.this) 或getApplicationContext() 都通吃。
//  "123" 為訊息,這邊要字串型態
//  Toast.LENGTH_LONG 顯示的維持時間,目前是它內定,也可以輸入秒數(單位: 1/1000秒)。
//  .show() 這樣它才會顯示在螢幕。



顯示結果





沒有留言:

張貼留言