问题:今天使用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()方法放最后就可对控件设置的方法都确定话。