我已按照此链接创建了一个网格视图
Android - Gridview with Custom BaseAdapter, get clicked View at position
工作正常。但我对cell.xml中的这两行感到困惑
android:clickable="false"
android:focusable="false"
这是假的,但是当我点击它时它正在工作,当我把它转为真时它不起作用。所以我很困惑,我有一些问题 -
• Why they are needed? When we generally create button we don’t define these two attribute. But I when create a button for grid view cell why it is needed?
• Why they work in reverse way?
• Is there any way to avoid these two line?
cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/grid_item"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="05"
android:textSize="20sp"
android:clickable="false"
android:focusable="false"/>
</Button>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private TextView text;
private GridView gridView;
private final String[] items = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.feedback);
gridView = (GridView) this.findViewById(R.id.myGridView);
CustomGridAdapter gridAdapter = new CustomGridAdapter(MainActivity.this, items);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
text.setText((String) (gridView.getItemAtPosition(position)));
Log.i("ITEM_CLICKED", "" + (String) (gridView.getItemAtPosition(position)));
}
});
}
}
CustomGridAdapter.xml
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private String[] items;
LayoutInflater inflater;
public CustomGridAdapter(Context context, String[] items) {
this.context = context;
this.items = items;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.cell, null);
}
Button button = (Button) convertView.findViewById(R.id.grid_item);
button.setText(items[position]);
return convertView;
}
@Override
public int getCount() {
return items.length;
}
@Override
public Object getItem(int position) {
return items[position];
}
@Override
public long getItemId(int position) {
return position;
}
}
答案 0 :(得分:1)
在大多数情况下,每个单元格的视图都没有任何可能消耗click事件的视图。因此,当您单击某一行时,GridView(或Listview)将调用onItemClickListener。
但是这里有一个可以默认点击的按钮。问题是GridView中的视图可以捕获click事件并阻止传播到gridview onItemClick事件。
因此,要避免按钮保留事件,您可以说它不应该是可点击的,具有属性clickable
。
单元格中的可点击元素可用于为每行提供多个可点击区域。