[英]how to add checkbox in listview in android?
我在Activity
使用了ListView
。 按照我的代码片段:
public class Home1 extends ListActivity {
private static final int ADD_MENU_ITEM = 1;
// private static final String TAG_COMPANY = "company";
private ProgressDialog pDialog;
SwipeRefreshLayout swipeLayout;
// URL to get contacts JSON
private static String url = "http://api-11hr.anovatesoft.com/v1/list";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CONTACT_NUMBER = "contactnumber";
private static final String TAG_POSTAL_CODE = "postalcode";
private static final String TAG_IMAGE = "image";
SessionManager session;
private double latitude;
private double longitude;
private String apikey;
GPSTracker gps;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
private String status;
private boolean doubleBackToExitPressedOnce;
private int c =1;
@Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// apikey
apikey = user.get(SessionManager.KEY_api);
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
/* swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
while (c != 1) {
onRefresh();
}*/
ImageView back = (ImageView) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Home1.this, Selected.class);
finish();
startActivity(intent);
}
});
ImageView profile = (ImageView) findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Home1.this, Setting.class);
startActivity(intent);
}
});
Gps_func();
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
//Set name and email in global/application context
apikey = globalVariable.getApikey();
status = globalVariable.getStatus();
latitude = globalVariable.getLatitude();
longitude = globalVariable.getLongitude();
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// lv.setItemsCanFocus(false);
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
// contactList.add(.get(position).toString());
String company = ((TextView) view.findViewById(R.id.company)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
String address = ((TextView) view.findViewById(R.id.address)).getText().toString();
String operating_hours = ((TextView) view.findViewById(R.id.operating_hours)).getText().toString();
String contact = ((TextView) view.findViewById(R.id.contact)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), Adds.class);
in.putExtra(TAG_NAME, company);
in.putExtra(TAG_USERNAME, description);
in.putExtra(TAG_ADDRESS, address);
in.putExtra(TAG_POSTAL_CODE, operating_hours);
in.putExtra(TAG_CONTACT_NUMBER, contact);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Gps_func() {
gps = new GPSTracker(Home1.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);
} else {
gps.showSettingsAlert();
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);
}
}
}
@Override
protected void onRestart() {
super.onRestart();
Gps_func();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Home1.this);
pDialog.setMessage("Please wait....");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler1 sh = new ServiceHandler1(apikey, latitude, longitude);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String contact_number = c.getString(TAG_CONTACT_NUMBER);
String postalcode = c.getString(TAG_POSTAL_CODE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
// contact.put(TAG_ADDRESS, address);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contact.put(TAG_USERNAME, username);
contact.put(TAG_POSTAL_CODE, postalcode);
contact.put(TAG_CONTACT_NUMBER, contact_number);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* in.putExtra(TAG_NAME, company);
in.putExtra(TAG_USERNAME, description);
in.putExtra(TAG_ADDRESS, address);
in.putExtra(TAG_POSTAL_CODE, operating_hours);
in.putExtra(TAG_CONTACT_NUMBER, contact);
* */
ListAdapter adapter = new SimpleAdapter(
Home1.this, contactList,
R.layout.list_item1, new String[]{TAG_NAME, TAG_USERNAME, TAG_ADDRESS, TAG_POSTAL_CODE, TAG_CONTACT_NUMBER,
}, new int[]{
R.id.company, R.id.description, R.id.address, R.id.operating_hours, R.id.contact});
setListAdapter(adapter);
}
}
/* @Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
contactList.clear();
new GetContacts().execute();
swipeLayout.setRefreshing(false);
}
}, 5000);
}*/
我想在我的ListView中添加CheckBox
,并在另一个Activity中通过CheckBox显示所选项目。 但是我不知道该怎么做。 我怎样才能做到这一点?
我认为这段代码与您的情况类似
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
db = new DatabaseHandlerChecklist(this);
initList();
add = (ImageButton) findViewById(R.id.addChecklist);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder add = new AlertDialog.Builder(
ChecklistActivity.this);
add.setTitle("Add checklist");
add.setIcon(R.drawable.alert_icon);
add.setMessage("Enter text : ");
final EditText content = new EditText(ChecklistActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
content.setLayoutParams(lp);
add.setView(content);
add.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String SContent = content.getText().toString();
if (SContent.equalsIgnoreCase("")) {
Toast.makeText(ChecklistActivity.this, "Insert text first !", 2000).show();
} else {
Checklist check = new Checklist(SContent, 0);
db.insert(check);
adapter.add(check);
adapter.notifyDataSetChanged();
initList();
Toast.makeText(ChecklistActivity.this, "Text added !", 2000).show();
}
}
});
add.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
add.show();
}
});
delete = (ImageButton) findViewById(R.id.deleteChecklist);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.delete();
adapter.notifyDataSetChanged();
initList();
Toast.makeText(ChecklistActivity.this, "Deleted !", 2000).show();
}
});
}
public void initList() {
list = db.getAll();
adapter = new ChecklistAdapter(this, R.layout.content_checklist, list);
ListView checklist = (ListView) findViewById(R.id.list);
checklist.setAdapter(adapter);
}
private class ChecklistAdapter extends ArrayAdapter<Checklist> {
Context context;
List<Checklist> checklist = new ArrayList<Checklist>();
int layoutResourceId;
public ChecklistAdapter(Context context, int layoutResourceId,
List<Checklist> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.checklist = objects;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBox chk = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.content_checklist,
parent, false);
chk = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(chk);
chk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Checklist changeChecklist = (Checklist) cb.getTag();
changeChecklist.setStatus(cb.isChecked() == true ? 1 : 0);
db.update(changeChecklist);
}
});
} else {
chk = (CheckBox) convertView.getTag();
}
Checklist current = checklist.get(position);
chk.setText(current.getContent());
chk.setChecked(current.getStatus() == 1 ? true : false);
chk.setTag(current);
return convertView;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater floatMenu = getMenuInflater();
floatMenu.inflate(R.menu.float_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about :
Intent change = new Intent("com.interactive.writeit.ABOUT");
startActivity(change);
break;
case R.id.help :
Intent change1 = new Intent("com.interactive.writeit.HELP");
startActivity(change1);
break;
case R.id.exit :
AlertDialog.Builder exit = new AlertDialog.Builder(this);
exit.setTitle("Exit");
exit.setMessage("Are you sure want to exit ?");
exit.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
exit.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
exit.show();
}
return false;
}
您必须创建包含您的ListView内容(包含Checkbox和TextView)的Checklist对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.