for循环中添加点击事件的正确写法
前言: 我们通常在写自定义控件向ViewGroup中动态添加View的时候,有时候没个View都要有它的点击事件。我们可以在for循环中依次添加当前View的点击事件,但是,就造成了资源的浪费。因为,假如我们循环了10次,它就new了10个点击对象,但实际最后只用了最后一个。
错误姿势
for (int i =
0
final TextView textView = new TextView(activity)
textView
.setGravity(Gravity
.CENTER)
textView
.setText(listBean
.getPhraseList()
.get(i)
.getContent())
textView
.setTextSize(text_size)
textView
.setTextColor(activity
.getApplicationContext()
.getResources()
.getColor(R
.color.black))
textView
.setBackgroundDrawable(activity
.getApplicationContext()
.getResources()
.getDrawable(R
.drawable.fast_words_bg))
textView
.setPadding(text_padding, text_padding, text_padding, text_padding)
flowLayout
.addView(textView)
textView
.setOnClickListener(new View
.OnClickListener() {
@Override
public void onClick(View view) {
//do something
}
})
}
正确姿势
for (int i =
0
final TextView textView = new TextView(activity)
textView
.setGravity(Gravity
.CENTER)
textView
.setText(listBean
.getPhraseList()
.get(i)
.getContent())
textView
.setTextSize(text_size)
textView
.setTextColor(activity
.getApplicationContext()
.getResources()
.getColor(R
.color.black))
textView
.setBackgroundDrawable(activity
.getApplicationContext()
.getResources()
.getDrawable(R
.drawable.fast_words_bg))
textView
.setPadding(text_padding, text_padding, text_padding, text_padding)
flowLayout
.addView(textView)
textView
.setOnClickListener(itemClick)
//给View做tag标记
textView
.setTag(i)
}
View
.OnClickListener itemClick=new View
.OnClickListener() {
@Override
public void onClick(View view) {
if (RoomActivity
.instance != null) {
int position= (int) view
.getTag()
TextView textView= (TextView) flowLayout
.getChildAt(position)
//do something
}
}
}
此方式是先遍历的时候将所有的View进行tag标记其position,再在循环外创建点击事件,通过View的tag获取这个View对象,再进行对应的点击效果。