如何使用android studio删除GridView中单击的单词?

时间:2016-10-02 21:40:21

标签: android gridview

您好我想从Gridview中删除点击的单词,但我不知道怎么做? 例如,如果我想删除例如" house"我应该点击它,它将被删除。 我尝试使用onclick但是我收到了错误。

mainActivity:
package com.example.hi.myapplication;

import android.app.Activity;
import android.os.Bundle;

import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import java.util.ArrayList;

public class MainActivity extends Activity {

GridView gv;
ArrayList<String> names = new ArrayList<String>();
ArrayAdapter<String> adapter;

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

    names.add("hi");
    names.add("go");
    names.add("went");
    names.add("house");
    names.add("home");
    names.add("blind");
    names.add("ears");
    names.add("hear");


    gv = (GridView) findViewById(R.id.gridview_id);

    //adapter
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
    gv.setAdapter(adapter);
}
}

我的xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.hi.myapplication.MainActivity">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView"
        android:numColumns="auto_fit"
        android:id="@+id/gridview_id" />
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

首先设置OnItemClickListener,然后在块内添加代码以删除项

gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

           names.remove(position);              
           adapter.notifyDataSetChanged();

        }
    });