我使用json从远程数据库检索数据,并且已经使用此数据创建了自定义listView。我有三个TextView和一个CheckBox,它工作得很好。所以,我添加了一个按钮,可以控制列表中的所选项目,并最终在另一个活动中传输所选项目。问题按照建议解决了,但如果我滚动列表,选定的项目会丢失状态。我认为这取决于可能性或适配器。有人能帮我吗?这是我的代码
public class Activity2 extends ActionBarActivity implements OnItemClickListener {
TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
list = (ListView) findViewById(R.id.listView);
currIntent = getIntent();
txtLavorante = (TextView) findViewById (R.id.Lavorante);
txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
stampaValori();
list_serv = new ArrayList<HashMap<String,String>>();
getData();
}
@Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
TextView tv = (TextView) v.findViewById(R.id.textView);
cb.performClick();
if (cb.isChecked()) {
checkedValue.add(tv.getText().toString());
Log.i("Btn Test",""+checkedValue);
} else if (!cb.isChecked()) {
checkedValue.remove(tv.getText().toString());
}
}
private void stampaValori() {
String pkg = getApplicationContext().getPackageName();
String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
String tNome = "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
txtLavorante.setText(tNome);
txtCodice.setText(tCode);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String time = c.getString(TAG_TIME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_PRICE,price);
persons.put(TAG_TIME,time);
list_serv.add(persons);
}
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
list.setOnItemClickListener(Activity2.this);
Button b= (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
Log.i ("Test ",""+checkedValue);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.example.com/.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.i ("Servizi","serv:"+result);
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity2.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListatoAdapter
public class ListatoAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
itemChecked = new boolean [dataList.size()];
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.prenota_serv, null);
holder = new ViewHolder();
holder.service = (TextView)convertView.findViewById(R.id.et_serv);
holder.id = (TextView)convertView.findViewById(R.id.et_id);
holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.service.setText(dataList.get(position).get("Descrizione"));
holder.id.setText(dataList.get(position).get("ID"));
holder.costo.setText(dataList.get(position).get("Costo"));
holder.durata.setText(dataList.get(position).get("Durata_m"));
holder.Ceck.setChecked(false);
if (itemChecked[position])
holder.Ceck.setChecked(true);
else
holder.Ceck.setChecked(false);
holder.Ceck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.Ceck.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
Log.i("Adapter Test",""+itemChecked[position]);
}
});
return convertView;
}
class ViewHolder {
TextView service;
TextView id;
TextView costo;
TextView durata;
CheckBox Ceck;
}
}
Activity2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">
<TextView android:text="hello_word" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Lavorante"
android:textStyle="bold"
android:textSize="22dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/CodiceLavorante"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView" />
prenota_serv.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Servizio:"
android:textSize="7pt"
android:id="@+id/tv_serv"
android:layout_alignBottom="@+id/tv_id"
android:layout_alignLeft="@+id/tv_id"
android:layout_alignStart="@+id/tv_id" />
<EditText
android:background="@android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="190dip"
android:id="@+id/et_serv"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignBottom="@+id/et_id"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Costo Euro:"
android:textSize="7pt"
android:id="@+id/tv_cost"
android:layout_below="@+id/et_serv"
android:layout_alignLeft="@+id/tv_serv"
android:layout_alignStart="@+id/tv_serv" />
<EditText
android:background="@android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="120dip"
android:id="@+id/et_costo"
android:layout_gravity="center_horizontal"
android:layout_below="@+id/et_serv"
android:layout_alignLeft="@+id/et_serv"
android:layout_alignStart="@+id/et_serv"
android:textSize="7pt" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Durata min:"
android:textSize="7pt"
android:id="@+id/tv_dur"
android:layout_below="@+id/et_costo"
android:layout_alignLeft="@+id/tv_cost"
android:layout_alignStart="@+id/tv_cost" />
<EditText
android:background="@android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="@+id/et_dur"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignTop="@+id/tv_dur"
android:layout_alignLeft="@+id/et_costo"
android:layout_alignStart="@+id/et_costo" />
<TextView
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Nr:"
android:layout_marginLeft="5dip"
android:layout_marginRight="9dip"
android:layout_alignParentLeft="true"
android:textSize="10pt"
android:id="@+id/tv_id"
android:visibility="invisible" />
<EditText
android:background="@android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="@+id/et_id"
android:layout_gravity="center_horizontal"
android:layout_alignTop="@+id/tv_id"
android:layout_alignLeft="@+id/et_serv"
android:layout_alignStart="@+id/et_serv"
android:enabled="false"
android:elegantTextHeight="false"
android:visibility="invisible" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox"
android:layout_below="@+id/tv_dur"
android:layout_alignRight="@+id/et_serv"
android:layout_alignEnd="@+id/et_serv" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/tv_dur"
android:layout_alignStart="@+id/tv_dur" />
答案 0 :(得分:2)
当用户选中一个复选框时,将其相应的数据放入列表中。然后在按钮点击时发送包中的列表。并使用该键在另一个活动上接收它。
你需要创建一个像。
这样的列表ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
list_selected = new ArrayList<HashMap<String, String>>();
}
将侦听器更改为。
holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
HashMap<String,String> data = dataList.get(position);
if(isChecked){
addToSelected(data);
}else{
removeSelected(data);
}
}
});
private void addToSelected(HashMap contact){
if(!list_selected.contains(contact))list_selected.add(contact);
}
private boolean removeSelected(HashMap contact){
return list_selected.remove(contact);
}
public ArrayList<HashMap<String, String>> getSelectedItems(){
return list_selected;
}
以活动adapter.getSelectedItems();
访问列表。
将您的活动声明为全球
ListatoAdapter adapter;
以这种方式设置适配器。
adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);
并获取按钮中的列表单击为。
ArrayList<HashMap<String,String> list = adapter.getSelectedItems();