2014-10-25Android学习--------按钮点击事件的写法

本文深入探讨了Android应用中activity类的布局实现与事件监听机制,详细介绍了如何通过XML布局文件定义按钮,并在Java代码中实现点击事件响应。包括通过OnClickListener接口实现事件处理,以及如何使用Intent进行activity间的通信。文章提供了具体示例代码,帮助开发者更好地理解和实践Android应用开发中的关键概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上篇文章中介绍了一个main.xml的布局,这也是主进程的布局,现在来看看它的activity类:

源码:

import com.wust.healthfood.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class MainApp extends Activity implements OnClickListener {
	
	Button list=null;
	Button about=null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		
		list = (Button) this.findViewById(R.id.foodlistbtn);
		about = (Button) this.findViewById(R.id.aboutbutton);
		
		list.setOnClickListener(this);
		about.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.foodlistbtn:
			Intent intent = new Intent();
			intent.setClass(MainApp.this, FoodListView.class);
			startActivity(intent);
			list.setBackgroundResource(R.drawable.btn_food_list_active);
			break;

		case R.id.aboutbutton:
			Intent intent1 = new Intent();
			intent1.setClass(MainApp.this, About.class);
			startActivity(intent1);
			about.setBackgroundResource(R.drawable.btn_food_about_active);
			break;
		}
	}
	
	

}


1. 定义两个 按钮,分别对应布局文件中的Button1和Button3

        Button list=null;
Button about=null;
在onCreate(Bundle)函数里面通过

 list = (Button) this.findViewById(R.id.foodlistbtn);

about = (Button) this.findViewById(R.id.aboutbutton);找到他们


接下来就是监听事件了:

(一)让主类去实现OnClickListener未实现的方法

list.setOnClickListener(this);// 这里面this代表上下文  写完它只会需要实现OnClickListener未实现的方法

当布局文件中有很多id的时候,我们最好采用让主类去实现OnClickListener未实现的方法,也就是让MainApp去implements OnClickListener

        然后重载未实现的方法public void onClick(View v)

     

switch (v.getId()) {
case R.id.foodlistbtn:

//todo

break;

case R.id.aboutbutton:
//todo
break;
}


(二)在内部类中实现未实现的方法

		list.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
			}
		});

其实这两种方法并没有什么太大的区别,只是当很多控件需要监听事件的时候,最好采用让主类是实现未实现的方法,这样代码好管理。



2.activity之间的通信:

			Intent intent = new Intent();
			intent.setClass(MainApp.this, FoodListView.class);
			startActivity(intent);
采用Intent意图
setClass(当前的activity,目的activity)

然后调用startActivity(intent);即可


代码相当简单,很容易理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值