gpt4 book ai didi

android - 如何添加gridview setOnItemClickListener

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:00:17 36 4
gpt4 key购买 nike

我有一个带有 81 个按钮的 GridView。我想将 clicklistener 添加到此 gridview,但它不可用。我已经添加了 OnItemClickListener 但它不起作用,我不明白为什么。代码没有错误。唯一不起作用的是 OnItemClickListener。

我的 gridview child 上面有一个按钮 (gridview_members.xml);

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<Button
android:id="@+id/city"
android:layout_width="183dp"
android:layout_height="90dp"
android:textSize="19sp"
android:textStyle="bold"
android:text="Code\n\nCity"
android:gravity="center"
android:background="@drawable/city_btn_tablet" />

</RelativeLayout>

我的 ImageAdapter 类;

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
mContext = c;
}

public int getCount() {
return 81;
}

public Object getItem(int position) {
return null;
}

public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View gridView;

gridView =new View(mContext);

gridView = inflater.inflate(R.layout.gridview_members, null);

Button city = (Button) gridView.findViewById(R.id.city);

return gridView;
}

}

activity_main.xml 上的 Gridview 实现;

<GridView
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:gravity="center"
android:stretchMode="columnWidth"
android:numColumns="6" >
</GridView>

最后是我的 MainActivity.java 文件;

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));

gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}

最佳答案

GridView 是可点击的,无需在 GridView 中放置按钮。

要将监听器添加到网格,请添加以下代码:

// Implement On Item click listener
gridView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

switch (position) {
case 0:
break;
case 1:
break;

}
}
});

依此类推,您可以将案例中的所有数字相加。

关于android - 如何添加gridview setOnItemClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20191914/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com