Android development: setcontentview switch interface, custom display SQLite entries in listview with checkbox-Implementation

Source: Internet
Author: User

Problem Background:

I have a database in another activity, which contains several entries. The database stores the simplest string type "name" information. In another activity, I press the button to display a list with checkbox, display the name in the database, and then select multiple. Similar to the Folder deletion function.

The following is an implementation:

In the first part, create a new my_checkbox.xml file in the layout folder.

This layout is used to control how each row is displayed in the future listview. Here I show the name on the left and the check box checkbox on the right.

<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: Orientation = "horizontal">
<Textview
Android: Id = "@ + ID/item_text"
Android: textsize = "25dip"
Android: layout_weight = "1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"/>
<Checkbox
Android: Id = "@ + ID/item_check"
Android: textsize = "25dip"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: clickable = "false"
Android: focusable = "false"
Android: checkmark = "? Android: ATTR/listchoiceindicatormultiple "/>

</Linearlayout>

Note:

1. layout_weight = 1 in the textview above is used to display the leftmost name and rightmost checkbox.

2. Because the response priority of the checkbox is higher than that of the listview, you must disable the clickable and focuseable attributes of the checkbox. In the future, it will only be determined by clicking the item of the listview.

3. the checkmark of the checkbox is used to set the effect after the checkbox is selected.

Part 2: Create a new layout list_check.xml to display database entries. When you click in the main activity, it will switch to this interface.

<? XML version = "1.0" encoding = "UTF-8"?>

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: Orientation = "vertical">

 

<Button

Android: Id = "@ + ID/confirmbtn"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Android: text = "OK"/>

 

<Listview

Android: Id = "@ + ID/checklist"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

</Listview>

 

</Linearlayout>

Note:The button above is the confirmation button after several items are selected, and the return button is also returned to the main interface.

Part 3: Set the setcontentview method in the main activity to switch the page.

The layout file of the main activity is not provided here.

The code for the main activity is as follows:

// To implement the new layout, button mchosebtn = NULL; button mconfirmbtn = NULL; Boolean firstflag = true; listview list2 = NULL; view checklistview = NULL; view mainview = NULL; /** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); layoutinflater Inflater = This. getlayoutinflater (); checklistview = Inflater. inflate (R. layout. list_check, null); mainview = Inflater. inflate (R. layout. main, null); setcontentview (mainview); // listener for switching the layout (mchosebtn = (button) mainview. findviewbyid (R. id. chosebtn); mchosebtn. setonclicklistener (New buttonlistener (); setupviews ();} class buttonlistener implements onclicklistener {public void onclick (view v) {// todo auto-generated method stubswitch (v. GETID () {case R. id. chosebtn: jump2checklist (); break; case R. id. confirmbtn: String S = getcheckinfo (); showtoast ("the names you selected are:" + S); jump2main (); break; default: Break ;}}}

 

/* Switch to the main layout */Public void jump2main () {setcontentview (mainview); setupviews ();}

 

/* Switch to the selected Layout */Public void jump2checklist () {setcontentview (checklistview); If (firstflag) {mconfirmbtn = (button) checklistview. findviewbyid (R. id. confirmbtn); mconfirmbtn. setonclicklistener (New buttonlistener (); firstflag = false;} initchecklist ();}

Part 4: Write an adapter to listviewIn fact, it is very simple, that is, the above initchecklist function, including initializing listview and adapter. First look at the source code:

 

public void initCheckList(){list2 = (ListView)(checkListView).findViewById(R.id.checkList);list2.setItemsCanFocus(false);list2.setAdapter(new CheckListAdapter(this, cursor));    list2.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);    list2.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View view, int positon,long id) {// TODO Auto-generated method stubViewHolder vHolder = (ViewHolder) view.getTag();vHolder.check.toggle();isSelected.put(positon, vHolder.check.isChecked());}});}

The following is an adapter:

/* Set the adapter */public static Map <integer, Boolean> isselected for checklist; public class checklistadapter extends baseadapter {private context mcontext; private cursor mcursor; // constructor public checklistadapter (context, cursor) {mcontext = context; mcursor = cursor; isselected = new hashmap <integer, Boolean> (); for (INT I = 0; I <mcursor. getcount (); I ++) {isselected. put (I, false) ;}} public int getcount () {// todo auto-generated method stubreturn cursor. getcount ();} public object getitem (INT arg0) {// todo auto-generated method stubreturn NULL;} public long getitemid (INT arg0) {// todo auto-generated method stubreturn 0;} public view getview (INT position, view convertview, viewgroup arg2) {// todo auto-generated method stubviewholder holder = NULL; if (convertview = NULL) {holder = new viewholder (); layoutinflater Inflater = (layoutinflater) mcontext. getsystemservice (context. layout_inflater_service); convertview = Inflater. inflate (R. layout. my_checkbox, null); holder. TEXT = (textview) convertview. findviewbyid (R. id. item_text); holder. check = (checkbox) convertview. findviewbyid (R. id. item_check); convertview. settag (holder);} else {holder = (viewholder) convertview. gettag ();} mcursor. movetoposition (position); holder. text. settext (integer. tostring (mcursor. getint (0); holder. text. append (mcursor. getstring (1); holder. check. setchecked (isselected. get (position); Return convertview;} public final class viewholder {public textview text; Public checkbox check ;}}

Note:

1. Set the corresponding parameters in initchecklist, such as multiple options.

2, public static Map <integer, Boolean> isselected; this isGlobal VariablesAnd is static, used to store the checkbox selected status. The http://mobile.51cto.com/android-254823.htm here sets it to a static variable in the adapter, But the strange thing is that I am not in the middle of it, and now it is global.

3. initialize the above variable in the constructor of the adapter and set all variables to unselected ones.

Isselected = new hashmap <integer, Boolean> ();

For (INT I = 0; I <mcursor. getcount (); I ++ ){

Isselected. Put (I, false );

4, because I have been associated with the database, so in the adapter constructor to transfer a cursor, understanding about the cursor can refer to the http://www.cnblogs.com/TerryBlog/archive/2010/07/05/1771459.html said that he is a set of information, is a collection. You can use cursor. getcount to obtain information about the number of rows. Cursor. movetoposition (I) locates row I. The method for obtaining data is related to the structure of the table created at the time of data creation.

5,

Public final class viewholder {

Public textview text;

Public checkbox check;

}

As for this viewholder, you do not need to use it. He just sets the elements of each row into a bit, which corresponds to the layout. However, in the future, we will use view. settag () and view. gettag () to transmit data, so I added it again.

6. Two key points of the adapter.

The first one is:

Public int getcount (){

// Todo auto-generated method stub

Return cursor. getcount ();

}

Here is the number of rows in the list. CallListview. getcount ()Actually, this function is called.

The second is: Public view getview (INT position, view convertview, viewgroup arg2) function. Note that the second parameter convertview is the layout for each row. Pass

Layoutinflater Inflater = (layoutinflater) mcontext. getsystemservice (context. layout_inflater_service );

Convertview = Inflater. Inflate (R. layout. my_checkbox, null );

Associate the first layout file with the view. Convertview. settag (holder) is actually a way to label the view, that is, to transmit data. When the layout is not empty, use holder = (viewholder) convertview. gettag (); to directly obtain the layout. Mcursor contains information about all rows,

Mcursor. movetoposition (position); this sentence positions it to the position,

Holder. Text. settext (integer. tostring (mcursor. getint (0 )));

Holder. Text. append (mcursor. getstring (1 ));

These two statements are used to obtain the information of each line. The structure of this table is that the first column (corresponding to index 0) is an int, and the second column (Index 1) is a string.

Holder. Check. setchecked (isselected. Get (position); this statement sets the checkbox status. That is to say, isselected is used to set that the initial state is not all selected. Therefore, it is not selected by default during each jump.

Finally, the program return convertview; returns this view. Then, when it is called next time, it is passed in as a parameter.

7. Explain the settings of the listview listener:

List2.setonitemclicklistener (New onitemclicklistener (){

 

Public void onitemclick (adapterview <?> Arg0, view, int positon,

Long ID ){

// Todo auto-generated method stub

Viewholder vholder = (viewholder) view. gettag ();

Vholder. Check. Toggle ();

Isselected. Put (positon, vholder. Check. ischecked ());

}

});

When each item is clicked, view is obtained through the clicked view. gettag, And the checkbox status is reversed.

Isselected. Put (positon, vholder. Check. ischecked (); this statement updates the isselected that saves information by accessing the status of the position checkbox.

8,Finally, how can I obtain the selected information?

This can be written as follows:

OnClickListener bPop = new OnClickListener() {            @Override            public void onClick(View v) {                for(int i=0;i<list.getCount();i++){                    if(MyAdapter.isSelected.get(i)){                        ViewHolder vHollder = (ViewHolder) list.getChildAt(i).getTag();    Log.i(TAG, "--onClick --"+vHollder.title.getText());                    }                }            }        }; 

Traverse through list. getcount, get the selected viewholder through list. getchildat (I). gettag, and get the information. Because I am hooked up with the database, I can directly read the information in the cursor.

My statement is:

public String getCheckInfo(){String info = "";for(int i=0; i<list2.getCount(); i++){if(isSelected.get(i)){//ViewHolder holder = (ViewHolder)list2.getChildAt(i).getTag();cursor.moveToPosition(i);info+=cursor.getInt(0)+".";}}return info;}

The above list2.getcount and cursor. getcount have the same effect.

 

Finally, let's talk about this cursor. Because it contains information about all rows in the database, I use it to fill every item directly. If the filled information is other, other data structures are used, such as list <Map <string, Object> mdata;, to save the information. Specific can refer to: http://mobile.51cto.com/android-254823.htm

Http://blog.csdn.net/a859522265/article/details/8204646 http://www.linuxidc.com/Linux/2011-11/47179p2.htm http://blog.sina.com.cn/s/blog_65570a20010108lp.html http://bbs.csdn.net/topics/330062289 I mainly refer to the first article.

 

In addition, how does one obtain the cursor in the database?

Cursor = mpalmdb. Select ();

The encapsulation of the select () function is:

public Cursor select(){SQLiteDatabase db = this.getReadableDatabase();Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);return cursor;}

This can be encapsulated in the database class or written to the function.

The source code, along with database operations, will be provided in another day!

 

:

1. Main Interface

 

2. After adding two data entries to the database:

3. Click the "selected" button above to switch to another interface.

4. Select the two entries:

Source code download: http://download.csdn.net/detail/yanzi1225627/5226894

Android enthusiasts are welcome to join group 248217350. Remarks: Yanzi

---------------------------- This article is original. For more information, see Author: yanzi1225627.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.