为每一个条目加入点击事件监听器
gv_main.setOnItemClickListener(this);
须要当前Activity实现OnItemClickListener接口。同一时候实现public void onItemClick(AdapterView<?> parent, View view, int position,long id)方法
/**
* 当gridview的条目被点击的时候相应的回调
* parent : gridView
* view : 当前被点击条目的 LinearLayout
* position : 点击条目相应的位置
* id : 代表的行号
*/
@Override
public void onItemClick(AdapterView<?
> parent, View view, int position, long id) { Log.i(TAG, "点击的位置" + position); switch(position){ case 0 : Log.i(TAG, "进入手机防盗"); break; } }
设置长按“手机防盗”时,弹出编辑窗体(知识点:SharedPreferences)
gv_main.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?
> parent, final View view, int position, long id) { if(position == 0){ Builder builder = new Builder(MainActivity.this); builder.setTitle("设置"); builder.setMessage("请输入要更改的内容"); final EditText et = new EditText(MainActivity.this); et.setHint("请输入内容。长度在0-8之间"); builder.setView(et); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = et.getText().toString();//获取输入 if("".equals(name)){ Toast.makeText(getApplicationContext(), "内容不能为空", Toast.LENGTH_LONG).show(); return; }else if(name.length() > 8){ Toast.makeText(getApplicationContext(), "输入过长", Toast.LENGTH_LONG).show(); return; }else{ Editor editor = sp.edit(); editor.putString("lost_name", name); // 完毕数据的提交 editor.commit(); TextView tv = (TextView) view.findViewById(R.id.tv_main_name); tv.setText(name); } } }); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } return false; } }); }
长按后弹出界面效果及设置后的效果: