如何同时 select 两个列表项?具体来说只有两个项目不超过
How to select two list items at same time ? To be specific ONLY TWO items not more than that
我有一个如下图所示的列表视图。
现在我想 select 一次仅从列表视图中选择任意两个项目,然后将带有 Intent 的两个列表视图项目的值传递给下一个 activity.我怎样才能实现它。?
如果这两项都没有select设置验证?
适配器Class
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
主要Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
@Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
@Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
@Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
@Override
public void onListChanged() {
}
@Override
public void onMove(int position, float x) {
}
@Override
public void onStartOpen(int position, int action, boolean right) {
}
@Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
@Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
@Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
@Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我会使用 MultiChoiceModeListener
的动作模式。
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
有回调onItemCheckedStateChanged(ActionMode mode, int position, boolean checked)
.
您可以轻松获取已检查列表项的值ListView.getCheckedItemPositions
。所以你可以阻止选择,如果你已经选择了两个或者甚至一次传递所选的值(或 ids)而不需要任何努力。
你可以简单地在项目 selection 上放置一个指示物。
取一个变量say for ex.
int count = 0;
在将项目标记为 selected/deselected:
之前检查此变量
if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
这将使您一次只能 select 两项。
像这样修改您的适配器:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in
adapter and call it with an adapter object like : adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
问题 2 的回答:如果你想使用 ImageView 而不是文本颜色更改。执行与上述相同的操作,但将 TextView + Color 替换为 ImageView + Image。
编辑 3:
您从 Null 对象调用了 getSelected()
方法。像这样修改您的代码:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
我有一个如下图所示的列表视图。
现在我想 select 一次仅从列表视图中选择任意两个项目,然后将带有 Intent 的两个列表视图项目的值传递给下一个 activity.我怎样才能实现它。?
如果这两项都没有select设置验证?
适配器Class
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
主要Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
@Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
@Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
@Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
@Override
public void onListChanged() {
}
@Override
public void onMove(int position, float x) {
}
@Override
public void onStartOpen(int position, int action, boolean right) {
}
@Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
@Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
@Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
@Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我会使用 MultiChoiceModeListener
的动作模式。
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
有回调onItemCheckedStateChanged(ActionMode mode, int position, boolean checked)
.
您可以轻松获取已检查列表项的值ListView.getCheckedItemPositions
。所以你可以阻止选择,如果你已经选择了两个或者甚至一次传递所选的值(或 ids)而不需要任何努力。
你可以简单地在项目 selection 上放置一个指示物。
取一个变量say for ex.
int count = 0;
在将项目标记为 selected/deselected:
之前检查此变量if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
这将使您一次只能 select 两项。
像这样修改您的适配器:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in adapter and call it with an adapter object like :
adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
问题 2 的回答:如果你想使用 ImageView 而不是文本颜色更改。执行与上述相同的操作,但将 TextView + Color 替换为 ImageView + Image。
编辑 3:
您从 Null 对象调用了 getSelected()
方法。像这样修改您的代码:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}