[Learn Android while working on projects] mobile security guard 05_2: main interface of the program, adding events for each entry, android05_2
Add a click event listener for each entry
gv_main.setOnItemClickListener(this);
The current Activity needs to implement the OnItemClickListener interface and public void onItemClick (AdapterView <?> Parent, View view, int position, long id) Method
/*** Callback * parent: gridview * view: LinearLayout * position: the position of the currently clicked entry * id: the row number */@ Override public void onItemClick (AdapterView <?> Parent, View view, int position, long id) {Log. I (TAG, "click position" + position); switch (position) {case 0: Log. I (TAG, "entering mobile phone anti-theft"); break ;}}
When you set the long-pressed "Mobile Phone anti-theft", the edit window is displayed (knowledge point: 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 ("set"); builder. setMessage ("Enter the content to change"); final EditText et = new EditText (MainActivity. this); et. setHint ("Enter the content in the range of 0-8"); builder. setView (et); builder. setPositiveButton ("OK", new OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {String name = et. getText (). toString (); // obtain the input if ("". equals (name) {Toast. makeText (getApplicationContext (), "content cannot be blank", Toast. LENGTH_LONG ). show (); return;} else if (name. length ()> 8) {Toast. makeText (getApplicationContext (), "the input is too long", Toast. LENGTH_LONG ). show (); return;} else {Editor editor = sp. edit (); editor. putString ("lost_name", name); // submit the data editor. commit (); TextView TV = (TextView) view. findViewById (R. id. TV _main_name); TV. setText (name) ;}}); builder. setNegativeButton ("cancel", new OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {}}); builder. create (). show () ;}return false ;}});}
After a long press, the page effect and the set effect are displayed: