Android使用LayoutInflator遇到的Button无触发事件问题

问题:今天使用LayoutInflator获取布局中的Button,然后给其添加事件,但是添加的触发事件没有响应。

详细:

过滤布局文件中的布局:

setContentView(R.layout.lose_pick);
LayoutInflater inflater = LayoutInflater.from(LosePickActivity.this);
View losePickView = inflater.inflate(R.layout.lose_pick, null);
通过上面两行代码获取R.layout.lose_pick中的布局。然后使用findViewById的方法得到想要的布局,从而获得布局中的控件。

LinearLayout buttonLayout = (LinearLayout) losePickView
				.findViewById(R.id.lose_lock_button_layout);
okBtn = (Button) buttonLayout.findViewById(R.id.okbtn);
cancelBtn = (Button) buttonLayout.findViewById(R.id.cancelbtn);
resetBtn = (Button) buttonLayout.findViewById(R.id.resetbtn);

okBtn.setOnClickListener(okOnClickListener);
cancelBtn.setOnClickListener(cancelOnClickListener);
resetBtn.setOnClickListener(resetOnClickListener);
我的是获取布局中的Button控件同时给button添加触发事件,但是一直没有响应。

解决方法:

把上面的红色部分setContentView()方法放到OnCreate()方法的最后面就可以解决了。

正确的:

public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SysApplication.getInstance().addActivity(this);
//		setContentView(R.layout.lose_pick);

		LayoutInflater inflater = LayoutInflater.from(LosePickActivity.this);
		View losePickView = inflater.inflate(R.layout.lose_pick, null);

		LinearLayout buttonLayout = (LinearLayout) losePickView
				.findViewById(R.id.lose_lock_button_layout);
		okBtn = (Button) buttonLayout.findViewById(R.id.okbtn);
		cancelBtn = (Button) buttonLayout.findViewById(R.id.cancelbtn);
		resetBtn = (Button) buttonLayout.findViewById(R.id.resetbtn);

		okBtn.setOnClickListener(okOnClickListener);
		cancelBtn.setOnClickListener(cancelOnClickListener);
		resetBtn.setOnClickListener(resetOnClickListener);
		
		setContentView(losePickView);
	}
把setContentView方法放在最后,同时参数是上面代码第二红行的变量。

我感觉导致问题的原因可能是当一开始设置setContentView(R.layout.lose_pick)即把布局文件中的控件“占有”了,而当使用LayoutInflater调用R.layout.lose_pick布局中的控件时,只能获得已经确定的,当时新添加的触发事件无法添加上。因此只需把setContentView()方法放最后就可对控件设置的方法都确定话。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值