在上篇文章中介绍了一个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;
}
}
}
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);即可
代码相当简单,很容易理解