使用< include>时如何使用Onclick事件标签 [英] How to use Onclick event when using <include> tag
问题描述
我两个班都有两个 java类和两个布局.
每个布局中都有一个按钮.
这两个类都扩展了Activity
.
现在在第一种布局中,我使用了这样的 include 标签
I have two java class and two layout for both the class.
Each layout is having one button in it.
Both classes are extending Activity
.
Now in first layout I used include tag like this
<include
android:id="@+id/clicked"
layout="@layout/activity_main" />
我现在可以看到两个按钮,但是第二个按钮不起作用.
I can now see two buttons but the second button is not working.
推荐答案
首先您必须声明并初始化 include 视图,然后使用 view.findViewById()方法如下:
First You have to declare and initialise the include view and then decalre and initialise both buttons using view.findViewById() method as follows:
View includeView = (View)findViewById(R.id.clicked);
Button button1 = (Button)includeView.findViewById(R.id.button1ID); //decalre button like this
Button button2 = (Button)includeView.findViewById(R.id.button2ID);
然后设置其 onClickListeners
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//code whatever you want to do here
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//code whatever you want to do here
}
});
**编辑**
解决了错字问题.应为 findViewById 上的 includeView . 很好的解释!
Fixed the typo. Should be includeView on the findViewById. Good explanation though!
这篇关于使用< include>时如何使用Onclick事件标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!