久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

新聞中心

EEPW首頁 > 嵌入式系統 > 設計應用 > Android 給Button加個監聽

Android 給Button加個監聽

作者: 時間:2016-10-08 來源:網絡 收藏

在Android開 發過程中,Button是常用的控件,用起來也很簡單,你可以在界面xml描述文檔中定義,也可以在程序中創建后加入到界面中,其效果都是一樣的。不過最 好是在xml文檔中定義,因為一旦界面要改變是話,直接修改一下xml就行了,不用修改Java程序,并且在xml中定義層次分明,一目了然。另一個是如 果在程序中定義,還要將其加入到界面中,有的還要設置高度寬度,樣式之類的,會使程序變得臃腫,開發和維護都不方便。

本文引用地址:http://cqxgywz.com/article/201610/305513.htm

我們先在程序中定義一個Button

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

button.setWidth(100);//一定要設置寬和高。不然會出錯的。

button.setHeight(50);

button.setText(“Click me”);//按鈕上的文字

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

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

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

android:orientation=”horizontal”

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();

}

});

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



關鍵詞:

評論


相關推薦

技術專區

關閉