我在谷歌上和这里的堆栈溢出处都经历了许多ariticles,但我似乎找不到解决问题的方法。我将要放在下面的代码片段是我研究并决定扩展它的教程。我曾尝试将listview转换为多选listview,但似乎无法绕过它。我不想创建一个包含复选框的自定义适配器,因为这对我来说会更复杂
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.180.35.102/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE="price";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
/** @Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
**/
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME,TAG_PRICE},
new int[] { R.id.pid, R.id.name, R.id.price });
// updating listview
setListAdapter(adapter);
//getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
});
}
以下是list_item.xml 的xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold"
/>
<!---price label-->
<TextView
android:id="@+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="9dip"
android:textStyle="bold"
/>
</RelativeLayout>
以下是所有产品的Xml布局
<?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="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
请告诉我如何将多选复选列表添加到此代码中。我将非常感谢任何帮助
维护两个布尔变量数组,一个是临时的,另一个是类成员,用户单击复选框ok按钮后将其存储在类变量中。
由于为加载值提供了代码,用户通过ok按钮确认。
void showMyMultipleChoiceDialog()
{
final boolean[] sel1 = new boolean[allusers.size()];
for (int i = 0; i < sel.length; i++)
{
sel1[i] = sel[i];
}
AlertDialog.Builder builderMultiple = new AlertDialog.Builder(DetailsTaskIncompleteActivity.this);
builderMultiple.setIcon(R.drawable.ic_launcher);
builderMultiple.setTitle("Select Users");
builderMultiple.setMultiChoiceItems(userlist, sel1, new DialogInterface.OnMultiChoiceClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked)
{
}
});
builderMultiple.setPositiveButton("Done", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
// users.delete(0, users.length());
for (int i = 0; i < sel.length; i++)
{
sel[i] = false;
}
users.setLength(1);
for (int i = 0; i < sel1.length; i++)
{
if (sel1[i] == true)
{
users.append(userlist[i] + ",");
sel[i] = true;
}
}
}
});
builderMultiple.show();
}
编写自定义适配器将是处理此问题的正确方法,因为这样您就更灵活了(请参阅:模型视图控件)。但是,如果您没有心情使用此解决方案,您可以简单地为productsList的每个项目手动填充复选框视图。
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
ViewGroup list = findViewById(R.id.list);
for(Map map : productsList){
ViewGroup parent = getLayoutInflater().inflate(R.id.list_item, null);
CheckBox cbview = new CheckBox(getContext);
//setup the cbview with the necessary attributes from map
parent.addView(cbview);
list.addView(parent);
}
}
});
}