package com.example.wang.testapp2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TestActivity10 extends AppCompatActivity {
GridView gv_1;
List<Integer> liv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test10);
//1-数据
liv=new ArrayList<>();
liv.add(R.drawable.f1);
liv.add(R.drawable.f2);
liv.add(R.drawable.f3);
liv.add(R.drawable.f4);
liv.add(R.drawable.f5);
liv.add(R.drawable.f6);
liv.add(R.drawable.f7);
liv.add(R.drawable.f8);
final ImageAdapter im=new ImageAdapter();
gv_1=(GridView)findViewById(R.id.gv_1);
gv_1.setAdapter(im);
gv_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(TestActivity10.this, "被点击的图片索引" + position, Toast.LENGTH_SHORT).show();
}
});
//长按删除的监听器
gv_1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//1.实现删除数据
//从集合里删除长按的那一条
liv.remove(position);
//2.刷新视图,看到效果
//通知适配器,数据源改变了
im.notifyDataSetChanged();
Toast.makeText(TestActivity10.this, "删除了记录索引=" + position, Toast.LENGTH_SHORT).show();
return true;//事件已经被消费,不要在处理了
}
});
}
//适配器
class ImageAdapter extends BaseAdapter
{
@Override
public int getCount() {
return liv.size();
}
@Override
public Object getItem(int position) {
return liv.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//1-得到数据 图片的id
Integer ivid=liv.get(position);
//2-准备视图View
if (convertView==null)
{
convertView = new ImageView(TestActivity10.this);
}
//3-适配
//项目转换
ImageView imageView=(ImageView)convertView;
imageView.setImageResource(ivid);
// imageView.setMaxWidth(70);
// imageView.setMaxHeight(70);
imageView.setLayoutParams(new GridView.LayoutParams(120,120));
return imageView;
}
}
}