当前位置:操作系统 > 安卓/Android >>

Android按钮监几种方法

-------------------第一种,所有按钮受监听.
package gongzibai.co.cc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RE1Activity extends Activity implements

OnClickListener {

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  Button mButton = (Button) findViewById

(R.id.button1);
  Button mButton2 = (Button) findViewById

(R.id.button2);
  TextView mTextView = (TextView) findViewById

(R.id.textView1);
  mButton.setOnClickListener(this);
  mButton2.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  Toast.makeText(RE1Activity.this, "1000",

2000).show();

 }

}


----------------内部监听
public class AnonymousListener extends Activity
{
 EditText show;
 Button bn;
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  show = (EditText)findViewById(R.id.show);
  bn = (Button)findViewById(R.id.bn);
  //直接使用Activity作为事件易做图
  bn.setOnClickListener(new OnClickListener()
  {
   //实现事件处理方法 www.zzzyk.com
   @Override
   public void onClick(View v)
   {
    // TODO Auto-generated method

stub
    show.setText("bn按钮被单击了!");
   }  
  });
 }
}

-----------依靠XML
<Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="button5"
        android:text="Button" />


public void button5(View v)
 {
 
  Toast.makeText(RE1Activity.this, "button5",

2000).show();
 }


-------------外部监听
mButton4.setOnClickListener(LOVEYOU);}括号外建立

OnClickListener LOVEYOU = new Button.OnClickListener() {

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   Toast.makeText(RE1Activity.this, "50000",

2000).show();

  }

 };

 

 

---------------------监听方法

OnClickListener LOVEYOU;

 
 

LOVEYOU = new Button.OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(RE1Activity.this, "50000", 2000).show();

   }
  };
  mButton4.setOnClickListener(LOVEYOU);

 

 

摘自 gongzibai的专栏

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,