In development, the ListView can be said to be one of the most frequently used controls, but there are also a lot of problems with the ListView. When we use the custom layout of the ListView, if there is a button in the layout file of the item or a checkbox and other controls, and its child control, often encounter the various controls of the Click event Conflict Situation, So how do we deal with the focus conflict between these controls in the ListView?
For example, we have a button control with item
First, join us without setting any attributes on focus, such as focus, and the code is as follows
View Sourceprint?01.
@Override
02.
public
View getView(
int
position, View convertView, ViewGroup parent) {
03.
convertView = inflater.inflate(R.layout.item,
null
);
04.
05.
Button btnButton = (Button) convertView.findViewById(R.id.btn);
06.
btnButton.setOnClickListener(
new
OnClickListener() {
07.
08.
@Override
09.
public
void
onClick(View v) {
10.
11.
Toast.makeText(context,
"点击了按钮"
,
0
).show();
12.
13.
}
14.
});
15.
16.
return
convertView;
17.
}
To set the Onitemclicklistener event for a ListView
View Sourceprint?1.
@Override
2.
public
void
onItemClick(AdapterView<?> parent, View view,
int
position,
long
id) {
3.
Toast.makeText(context,
"点击了Item"
,
0
).show();
4.
}
View Sourceprint?1.
So in this case, we can trigger the button's Click event, but the item's click event is not triggered, that is, the button control robs the item of the focus event, so that item does not trigger the corresponding Click event, then, What should we do if we want to trigger the Click event of the button and want to trigger the item's Click event?
There are three types of solutions
1. Set the child control Focusable property in the item layout in the ListView to False
2. Set Button.setfocusable (False) in the GetView method
3. Set the property of the root layout of item android:descendantfocusability= "Blocksdescendant"
We can see that all three of these methods are designed so that buttons and other controls cannot get the focus, so that item can respond to click events.
The third method is relatively convenient to use because it sets all other controls in the item layout to not get the focus.
The Android:descendantfocusability attribute has a total of three values, respectively
Beforedescendants:viewgroup takes precedence over its subclass control and gets to focus
Afterdescendants:viewgroup gets focus only if its subclass control does not need to get focus
Blocksdescendants:viewgroup overrides the subclass control and gets the focus directly