我创建了包含两个文本字段和一个切换按钮的listview。我可以在打开切换按钮时从列表视图中获取文本,但问题是当我关闭我的应用程序或滚动列表视图时,我的切换按钮状态已更改。
以下是我的完整代码:
public class MainActivity extends Activity {
ArrayList<String> call_log_no;
ArrayList<String> call_log_name;
String strStatus = "";
//Array of booleans to store toggle button status
public boolean[] status;
StringBuffer sb;
String phNum,cname,details;
MatrixCursor mMatrixCursor;
ArrayList<String> choiceList;
ListView lvCountries;
HashMap<String,Object> hm;
int pos;
// Each row in the list stores country name and its status
List<HashMap<String,Object>> aList
= new ArrayList<HashMap<String,Object>> ();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/** Restore from the previous state if exists */
if(savedInstanceState!=null){
status = savedInstanceState.getBooleanArray("status");
}
call_log_no = new ArrayList<String>();
call_log_name = new ArrayList<String>();
choiceList = new ArrayList<String>();
lvCountries = (ListView) findViewById(R.id.lv_countries);
OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?>
lv, View item, int position, long id) {
ListView lView = (ListView) lv;
SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter();
HashMap<String,Object> hm = (HashMap) adapter.getItem(position);
/** The clicked Item in the ListView */
RelativeLayout rLayout = (RelativeLayout) item;
/** Getting the toggle button corresponding to the clicked item */
ToggleButton tgl = (ToggleButton) rLayout.getChildAt(0);
String strStatus = "";
if(tgl.isChecked()){
tgl.setChecked(false);
strStatus = "Off";
status[position]=false;
}else{
tgl.setChecked(true);
strStatus = "On";
status[position]=true;
}
Toast.makeText(getBaseContext(), (String) hm.get("no") + " : " + strStatus, Toast.LENGTH_SHORT).show();
}
};
lvCountries.setOnItemClickListener(itemClickListener);
// Each row in the list stores country name and its status
List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>();
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","details"} );
getCallDetails();
//Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{
@Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringExists = (call_log_no.contains(homePhone)||(call_log_no.contains("+91"+homePhone)));
if(isStringExists==true)
{
}
else{
call_log_no.add(homePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringE = (call_log_no.contains(mobilePhone)||(call_log_no.contains("+91"+mobilePhone)));
if(isStringE==true)
{
}
else{
call_log_no.add(mobilePhone);
call_log_name.add(displayName);
}
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
boolean isStringExis = (call_log_no.contains(workPhone)||(call_log_no.contains("+91"+workPhone)));
if(isStringExis==true)
{
}
else{
call_log_no.add(workPhone);
call_log_name.add(displayName);
}
break;
}
}
}while(dataCursor.moveToNext());
String details = "";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
@Override
protected void onPostExecute(Cursor result) {
status = new boolean[call_log_name.size()];
for(int i = 0,j = 0,k=0; i < call_log_name.size() ; i++,j++,k++)
{
HashMap<String, Object> hm = new HashMap<String,Object>();
status[k]=false;
// choiceList.add("\nName: "+call_log_name.get(i)+"\nPhone Number: " + call_log_no.get(j));
hm.put("no", call_log_no.get(i));
hm.put("txt", call_log_name.get(j));
hm.put("stat",status[k]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = {"txt","no","stat" };
// Ids of views in listview_layout
int[] to = {R.id.tv_item,R.id.tv_no, R.id.tgl_status};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.activity_main, from, to);
lvCountries.setAdapter(adapter);
}
}
请帮助我..我想保存所有切换按钮状态和与数据对应的文本
答案 0 :(得分:0)
最好按照以下方式接近列表视图。
创建一个类来保存listview数据。例如:
公共类国家{
private String mName; private boolean mChecked;
公共国家{ }
public String getName(){ return mName; }
public void setName(String name){ mName = name; }
public boolean isChecked(){ 返回mChecked; }
public void setChecked(boolean checked){
mChecked = checked;
}
}
public class CountriesListAdapter extends ArrayAdapter {
public CountriesListAdapter(Context context, int resource, ArrayList<Countries>countriesList) {
super(context, resource, countriesList);
}
@Override
public View getView(int position, View cell, ViewGroup parent) {
//Get an instance of our cell holder
Holder holder;
//If this is the first time the Listview is going to display this cell
//Create new Holder
if(cell == null)
{
Holder = new Holder();
//Get layout inflater service to inject our view in the listview cell
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cell = vi.inflate(R.layout.your_xml_layout, parent, false);
holder.textView = (TextView)cell.findViewById(R.id.textview);
holder.toggleButton = (ToggleButton)cell.findViewById(R.id.toggleButton);
//Attach the new cell to the listview row
cell.setTag(holder);
}else{
//The row was already created before to get it from the row
holder = (Holder)cell.getTag();
}
//Get item at current position
Countries country = getItem(position);
//Set row data
holder.textview.setText(country.getName());
holder.toggleButton.setChecked(country.isChecked());
//return the cell to the listview to dosplay
return cell;
}
//this holder class will be filled from the layout xml and attached
//to the row as a tag object
private class Holder{
TextView textView;
ToggleButton toggleButton;
}
}
在您的活动或片段中创建新的国家/地区项目数组后。
然后启动新适配器通过国家/地区列表。
将适配器设置为listview。
现在,在点击监听器上,您将获得给定位置的Country对象。
使用此方法,您可以滚动并切换切换按钮。