Android 給Button加個監聽

Android開 發過程當中,Button是經常使用的控件,用起來也很簡單,你能夠在界面xml描述文檔中定義,也能夠在程序中建立後加入到界面中,其效果都是同樣的。不過最 好是在xml文檔中定義,由於一旦界面要改變是話,直接修改一下xml就好了,不用修改Java程序,而且在xml中定義井井有條,一目瞭然。另外一個是如 果在程序中定義,還要將其加入到界面中,有的還要設置高度寬度,樣式之類的,會使程序變得臃腫,開發和維護都不方便。android

咱們先在程序中定義一個Buttonthis

Button button = new Button(this);//定義一個button,其中this是上下文,這段代碼是在一個Activity的onCreate中建立的。xml

button.setWidth(100);//必定要設置寬和高。否則會出錯的。blog

button.setHeight(50);事件

button.setText(「Click me」);//按鈕上的文字開發

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.buttonLayout);文檔

relativeLayout.addView(button);//加到界面中get

如下是在UI xml中定義的按鈕。it

android:orientation=」horizontal」io

android:layout_width=」fill_parent」

android:layout_height=」45px」

android:background=」#ffffff」

android:layout_alignParentBottom=」true」>

android:id=」@+id/button」

android:text=」 Click me」

android:layout_alignParentLeft=」true」

android:layout_alignParentBottom=」true」

android:layout_width=」100px」

android:layout_height=」50px」/>

接下來是要給按鈕加一個監聽了,就是響應點擊按鈕的事件。這個是在程序中完成了,

button.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

Toast toast = Toast.makeText(getApplicationContext(), 「I am Clicked」, Toast.LENGTH_LONG);//提示被點擊了

toast.show();

}

});

好了,按鈕就是這麼簡單。

來自 3G Study http://blog.3gstdy.com/

相關文章
相關標籤/搜索