本文實(shí)例講述了Android簡(jiǎn)單Button事件響應(yīng)綜合提示控件Toast應(yīng)用。分享給大家供大家參考,具體如下:
前面講述了在main.xml里定義了Button對(duì)象,這里我們來(lái)學(xué)習(xí)Button如何實(shí)現(xiàn)事件響應(yīng)。
Button按鈕所觸發(fā)的事件處理,我們稱之為Event Handle,只不過(guò)在Android當(dāng)中,按鈕事件是由系統(tǒng)的Button.OnClickListener所控制,熟悉Java程序設(shè)計(jì)的讀者對(duì)OnXxxListener應(yīng)該不陌生.以下的Demo,我們將實(shí)現(xiàn)當(dāng)點(diǎn)擊Button時(shí),TextView文字將發(fā)生改變,并在屏幕上出現(xiàn)一段時(shí)間的Toast提醒.
讓我們看一下效果圖:
點(diǎn)擊按鈕前:

點(diǎn)擊按鈕后:

我們主要在程序里改了兩處地方一處是main.xml 另一處是ButtonDemo.java
Main.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" //1.5以后默認(rèn)的是LinearLayout布局 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:id="@+id/textview1" //定義Id方便Java類找到它,并且控制它 android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /><Button android:id="@+id/button1" android:layout_width="60px" android:layout_height="wrap_content" android:layout_gravity="right" //讓Button放在右面 android:text="確定"/></LinearLayout>
Button.java 代碼如下:
package com.android.test;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class ButtonDemo extends Activity { private TextView textview1; private Button button1; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //通過(guò)ID在找到定義在main.xml里的TextView和Button控件 textview1 = (TextView)findViewById(R.id.textview1); button1 = (Button)findViewById(R.id.button1); //增加事件響應(yīng) button1.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { //Toast提示控件 Toast.makeText(ButtonDemo.this, "TextView里的文字發(fā)生了改變,你注意到了嗎?", Toast.LENGTH_LONG).show(); //將TextView的文字發(fā)生改變 textview1.setText("歡迎來(lái)到魏祝林的博客!"); } }); }}今天就到此為止。
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開(kāi)發(fā)入門與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫(kù)技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫(kù)操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開(kāi)發(fā)之SD卡操作方法匯總》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選