Android 多个include标签的监听事件处理

时间:2021-11-04 22:40:20

  include标签的作用是为了xml文件代码的模块化,详细不再多提。主要是说说include标签的监听。

  网上也有很多例子,不过大多是只写了一个include标签的监听,如果需要实现多个include标签的监听怎么做呢?我至少是没在百度搜出来,经过不断的尝试,修改,终于找到了方法,现在分享给大家,希望对大家有帮助。

  先介绍一点,就是include标签本身是不能设置监听的,不论是android:onClick 或者 是对 include 绑定监听器setOnClickListener,都不起作用(我的实验结果是这样,具体的没有查文档)。不论一个界面有多少个include,android系统只是对include标签里面的子标签监听,但由于子标签只有一个,所以无法区分监听结果,其实解决办法也很简单,只需要单独对include标签的每个子标签重新设置 id 即可。下面是代码:

需要复写的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width
="fill_parent"
android:layout_height
="wrap_content"
android:orientation
="vertical" >

<TextView
android:id
="@+id/sub_tv"
android:layout_width
="fill_parent"
android:layout_height
="45dp"
android:clickable
="true"
android:onClick
="onClick"
android:background
="#008800"
android:layout_marginTop
="10dp"
android:gravity
="center_vertical"
android:paddingLeft
="10dp"
android:paddingRight
="10dp"
android:text
="测试"
android:textSize
="17sp"
android:textColor
="#ffffff" />

</LinearLayout>

 

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:orientation
="vertical" >

<include
android:id
="@+id/item1"
layout
="@layout/sub_my_resume_item" />

<include
android:id
="@+id/item2"
layout
="@layout/sub_my_resume_item" />

<include
android:id
="@+id/item3"
layout
="@layout/sub_my_resume_item" />

<include
android:id
="@+id/item4"
layout
="@layout/sub_my_resume_item" />

</LinearLayout>

 

代码:

package com.example.testincludeonclick;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

private int[] id = { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

for (int i = 0; i < id.length; i++) {
View v
= findViewById(id[i]);
TextView tv
= (TextView) v.findViewById(R.id.sub_tv);
tv.setId(i);
tv.setText(
"测试 " + (i + 1));
}
}


public void onClick(View v) {
System.out.println(
"sub_id: " + v.getId());

switch (v.getId()) {
case 0:
Toast.makeText(getApplicationContext(),
"测试1", 1).show();
break;
case 1:
Toast.makeText(getApplicationContext(),
"测试2", 1).show();
break;
case 2:
Toast.makeText(getApplicationContext(),
"测试3", 1).show();
break;
case 3:
Toast.makeText(getApplicationContext(),
"测试4", 1).show();
break;

default:
break;
}
}

}

 运行结果:

Android  多个include标签的监听事件处理

 

Android  多个include标签的监听事件处理