Android GridView
程序员文章站
2022-05-12 09:18:26
...
需求:在Android移植的arm板子上实现图片用GridView展示,只用键盘操作。OS:android2.2.1
问题:如果焦点从GridView上的一个Item移出,使GridView失去焦点,当焦点返回GridView时,如果第一个获得焦点的Item是上次最后移出那个Item此时不会触发OnItemSelectedListener中的onItemSelected事件.
测试代码:
Activity代码:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView mGridView = (GridView) findViewById(R.id.gview); mGridView.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT) .show(); } public void onNothingSelected(AdapterView<?> arg0) { } }); BaseAdapter adapter = new BaseAdapter() { public int getCount() { return 6; } public Object getItem(int arg0) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ImageView mImageView = new ImageView(MainActivity.this); mImageView.setImageResource(R.drawable.icon); return mImageView; } }; mGridView.setAdapter(adapter); }
|
|
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text1Text1" android:focusable="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text2Text2" android:focusable="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text3Text3" android:focusable="true" /> </LinearLayout> <GridView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/gview" android:numColumns="4"></GridView> </LinearLayout>
只用键盘操作确实会出现问题所述情况.
解决方法:
查看源代码中GridView有一个default的方法setSelectionInt第次做Item选择以后会记录下这个Item的postion.在焦点丢失时清空把这个置为-1就可以达到想要的目的.
添加如下代码:
mGridView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
try {
@SuppressWarnings("unchecked")
Class<GridView> c = (Class<GridView>) Class
.forName("android.widget.GridView");
Method[] flds = c.getDeclaredMethods();
for (Method f : flds) {
if ("setSelectionInt".equals(f.getName())) {
f.setAccessible(true);
f.invoke(v,
new Object[] { Integer.valueOf(-1) });
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
这样还是会存在一个问题,GridView默认的获得的焦点位置是0,如果焦点进入GridView,第0个Item得到焦点也不会触发ItemSelected事件,可以在加载完GridView的时候使用上面反射的代码清除默认焦点,达到预期效果。
下一篇: Seekbar调节系统音量