在gridview中单击项目

时间:2014-05-11 16:14:34

标签: android xml gridview layout onclicklistener

如果一个.xml文件代表网格的一般视图而另一个文件代表该网格中的自定义项目,如何正确实现项目点击侦听器?

一般视图fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:verticalSpacing="0dp"
    android:horizontalSpacing="0dp"
    android:stretchMode="columnWidth"
    android:numColumns="2"
/>

并查看图片和textview gridview_item.xml的项目cosist:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.myapp.gridview.SquareImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"

    />
<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:layout_gravity="bottom"
    android:textColor="@android:color/white"
    android:background="#55000000"
    />
</FrameLayout>

android:onClick=""fragment_main中需要写gridview_item的位置?是否还需要启用gridview的其他所需属性?

感谢建议。

1 个答案:

答案 0 :(得分:1)

如果您正在处理该类中的BaseAdpaterArrayAdapter,那么您将使用getView方法返回View对象,您只需在该视图上写一个setOnClickListerner(converview)

查看以下可能对您有帮助的代码

    @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view=inflater.inflate(R.layout.group_row, null);
    view.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // your logic goes here 
       }
    });
    return view;
}