构建抽象Activity

1、在开发中,可以建立一个公共的Activity类,让所有其他的Activity继承这个类,在这个类中对头部和尾部的数据进行处理。

public abstract class BaseActivity extends Activity {

	private Button settingBtn;
	private TextView titleText;

	// 准备一个按钮的数组
	private Button[] bottomBtns = new Button[3];

	// 准备目标的Activity类
	private Class[] targetActvities = { MainActivity.class,
			QuestionListActivity.class, SearchActivity.class };
	// 准备按钮不选中的图片数组
	private int[] allBottomsImgs = { R.drawable.bottom_01_a,
			R.drawable.bottom_02_a, R.drawable.bottom_03_a };
	// 选中的图片数组
	private int[] allBottomsImgsSelected = { R.drawable.bottom_01_b,
			R.drawable.bottom_02_b, R.drawable.bottom_03_b };

	// 声明循环的i,为了在内部类中使用
	private int i;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	protected void init(String title, int selectedBtn) {
		// 分别取得这些组件
		settingBtn = (Button) findViewById(R.id.setting_btn);
		titleText = (TextView) findViewById(R.id.title_text);

		bottomBtns[0] = (Button) findViewById(R.id.bottom_01_btn);
		bottomBtns[1] = (Button) findViewById(R.id.bottom_02_btn);
		bottomBtns[2] = (Button) findViewById(R.id.bottom_03_btn);

		titleText.setText(title);

		// 循环为底部按钮加入监听
		for (i = 0; i < bottomBtns.length; i++) {
			// 临时定义几个变量, 防止i一直自增
			final int temp = i;
			if (i == selectedBtn) {
				// 选中的
				bottomBtns[i].setBackgroundResource(allBottomsImgsSelected[i]);
			} else {
				// 没有选中的
				bottomBtns[i].setBackgroundResource(allBottomsImgs[i]);
				// 加入监听
				bottomBtns[i].setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 加入切换界面的操作
						Intent in = new Intent(BaseActivity.this,
								targetActvities[temp]);
						startActivity(in);
					}
				});
			}
		}
	}
}

使用时,需要通过调用super.init()将需要的参数传递到里面,进行初始化。

super.init("全部问题",1);

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值