I need to create a custom alert dialog with single choice.
But items have their own layout:
[VIEW(just color)_______TEXT_______RADIOBUTTON]
I have created a custom layout for listview, custom adapter and have a nice result
But i cant make single choice, no one listener sets to listview...:
Here is my adapter :
public class AlertListAdapter extends BaseAdapter {
ArrayList<AlertChoiceItem> mData;
Context mContext;
LayoutInflater inflater;
public AlertListAdapter(ArrayList<AlertChoiceItem> data, Context context) {
mData = data;
mContext = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_alert_list, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitleAlertList);
View v = (View) convertView.findViewById(R.id.vPriorAlertList);
v.setBackgroundColor(GetColorByPriority.getColor(position, mContext));
tvTitle.setText(mData.get(position).getTitle());
RadioButton rb = (RadioButton) convertView.findViewById(R.id.rbRadioAlertList);
return convertView;
}
}
Here i create alert:
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
// dialog.setContentView(R.layout.alert_list_radio);
dialog.setTitle("List Title");
View customView = LayoutInflater.from(getActivity()).inflate(
R.layout.alert_list_radio, null, false);
ListView listView = (ListView) customView.findViewById(R.id.lvAlertList);
// ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
// R.layout.single_item_layout , R.id.singleItem, dummies);
ArrayList<AlertChoiceItem> itemList = new ArrayList<AlertChoiceItem>();
itemList.add(new AlertChoiceItem(false, "Critical", 5));
itemList.add(new AlertChoiceItem(false, "High", 4));
itemList.add(new AlertChoiceItem(false, "Medium", 3));
itemList.add(new AlertChoiceItem(false, "Low", 2));
itemList.add(new AlertChoiceItem(false, "Very low", 1));
itemList.add(new AlertChoiceItem(false, "Off filter", 0));
AlertListAdapter mAdapter = new AlertListAdapter(itemList, getActivity());
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(mOnItemClick);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
dialog.setView(customView);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
How to add single choice?
UPD:
AlertChoiceItem implen:
public class AlertChoiceItem {
private boolean isChecked;
private String title;
private int prior;
public AlertChoiceItem(boolean isChecked, String title, int prior) {
super();
this.isChecked = isChecked;
this.title = title;
this.prior = prior;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
}
Solve problem in such way:
1) Make all(!) views in layout not focusable.
2) Set onClickItemListener in activity to listview
3) With every click send to adapter signal to remove all checks, set new(by position)
and re-draw listview.
Set in item_alert_list xml file
android:focusable = "false"
android:focusableInTouchMode="false"
for your all UI elements.
You may try adding ItemClick listener to your listview
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// do whatever you want
}
});
Check your implementation of AlertChoiceItem. Make sure it implements the Checkable interface as well as passes it through to the underlying RadioButton you are using.
Related
This is my adapter class :
public class CheckboxAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
Context context;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
ArrayList<String> selectedStrings = new ArrayList<String>();
public CheckboxAdapter(Context ctx, int viewResourceId, String[] strings) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mViewResourceId = viewResourceId;
}
public int getCount() {
return mStrings.length;
}
public String getItem(int position) {
return mStrings[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
final CheckBox tv = (CheckBox) convertView.findViewById(R.id.checkBox1);
tv.setText(mStrings[position]);
tv.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
selectedStrings.add(tv.getText().toString());
Toast.makeText(buttonView.getContext(),Boolean.toString(selectedStrings.add(tv.getText().toString())), Toast.LENGTH_SHORT).show();
} else {
selectedStrings.remove(tv.getText().toString());
}
}
});
return convertView;
}
}
This is my actvity
public class AddTime extends Activity {
CheckboxAdapter cadpter;
String daya[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday",
"Friday", "Saturday" };
ListView list;
ArrayList<String> selectedStrings = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtime);
list = (ListView) findViewById(R.id.listView1);
cadpter = new CheckboxAdapter(AddTime.this, R.layout.list_item, daya);
list.setAdapter(cadpter);
}
}
I am displaying all day in listview also i have display check box with each day when i enable check box it show true in toast but i want what ever i select day using check box i mean i want display all the day in textview in mainactvity please suggest me how i will get it .
how to get all checked value on button click from list-view in android
As adding all checked values in selectedStrings ArrayList. create a method in CheckboxAdapter class which return ArrayList of all selected values. for example :
public ArrayList<String> getAllSelectedValues(){
return this.selectedStrings;
}
Now use cadpter CheckboxAdapter class object for accessing getAllSelectedValuesmethod in Activity:
ArrayList<String> selectedStrings=cadpter.getAllSelectedValues();
get all values from selectedStrings arrayList
for(int i=0;i<=selectedStrings.sizes();i++){
String s =selectedStrings.get(i);
}
Take boolean Array
ArrayList<Boolean> selectedStrings = new ArrayList<>();
and add onClickListener in your checkbox
public View getView(final int position, View convertView, ViewGroup parent) {
-
-
tv.setChecked(false);
if(selectedStrings.size() <= position){
selectedStrings.add(position, false);
}else
tv.setChecked(selectedStrings.get(position));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean state = selectedStrings.get(position);
selectedStrings.remove(position);
selectedStrings.add(position, state ? false : true);
}
});
}
I have a custom listview and spinner.First of all i am filling the listview and then i am clicking dropdown spinner.I am choosing a item(city).I want to update listview with new result.But whatever i can custom adapter getview is not call. So listview is not update. This is my screen
How can i do it?
I am filling spinner here
private void getCityListWithSpinner() {
cityListRequest = new CityListRequest(new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
System.out.println("Objemizzz " + obj.toString());
cityArrayList = (ArrayList<CityList>) obj;
Spinner ss = (Spinner) findViewById(R.id.cityfilmspinner);
CinemaCitySelector2 citySelector = new CinemaCitySelector2();
cityList.add("Seçiniz");
for (int i = 0; i < cityArrayList.size(); i++) {
cityList.add(cityArrayList.get(i).getCinemaCity());
citySelector.CinemaCitySelector2(
CinemaCityMoviePickerActivity.this, ss, cityList,2);
}
}
CinemaCitySelector:
public class CinemaCitySelector2 implements OnItemSelectedListener {
Context context2;
Spinner spinner2;
CityListInCityRequest cityListInCityRequest2;
ArrayList<Cinema> cityListInCityArrayList2;
ListView list_cinema_movie_selectorr2;
CinemaListViewAdapter2 adapter2;
View row2;
int act2 = 0;
Spinner cityspinner;
public void CinemaCitySelector2(Context context, Spinner spinner,
ArrayList<String> cityList, int activityfrom) {
this.context2 = context;
this.spinner2 = spinner;
act2 = activityfrom;
// Declaring an Adapter and initializing it to the data pump
ArrayAdapter adapter = new ArrayAdapter(context,
android.R.layout.simple_list_item_1, cityList);
// Setting Adapter to the Spinner
spinner.setAdapter(adapter);
// Setting OnItemClickListener to the Spinner
spinner.setOnItemSelectedListener(CinemaCitySelector2.this);
}
// Defining the Callback methods here
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
String city = spinner2.getItemAtPosition(pos).toString();
LayoutInflater layoutInflater = LayoutInflater.from(context2);
row2 = layoutInflater.inflate(
R.layout.activity_cinemacitymoviepicker, null, false);
list_cinema_movie_selectorr2 = (ListView) row2
.findViewById(R.id.listfilmincinema);
if (!city.equals("Seçiniz")) {
cityListInCityRequest2 = new CityListInCityRequest(
new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
// adapter.clear();
// adapter.notifyDataSetChanged();
// list_cinema_movie_selector.setAdapter(adapter);
System.out.println("Objemizzz " + obj.toString());
cityListInCityArrayList2 = (ArrayList<Cinema>) obj;
// adapter.notifyDataSetChanged();
adapter2 = new CinemaListViewAdapter2(context2,
R.layout.cinema_list,
cityListInCityArrayList2);
list_cinema_movie_selectorr2
.setAdapter(adapter2);
}
#Override
public void asyncOperationFailed(Object obj, int queue) {
// TODO Auto-generated method stub
System.out.println("Objemizzz2 " + obj.toString());
}
}, city);
}
}
public void onNothingSelected(AdapterView arg0) {
// TODO Auto-generated method stub
}
}
CinemaListViewAdapter2:
public class CinemaListViewAdapter2 extends ArrayAdapter<Cinema> {
Context context;
int arraycount=0;
public CinemaListViewAdapter2(Context context, int resourceId,
ArrayList<Cinema> items) {
super(context, resourceId, items);
this.context = context;
arraycount=items.size();
}
/*private view holder class*/
private class ViewHolder {
BlackBrandTextview cinemaName;
RelativeLayout cinemalist;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Cinema rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.cinema_list, null);
holder = new ViewHolder();
holder.cinemaName = (BlackBrandTextview) convertView.findViewById(R.id.txt_cinema_name);
holder.cinemalist=(RelativeLayout)convertView.findViewById(R.id.cinemalist);
holder.cinemaName.setText(rowItem.getCinemaName());
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
holder.cinemaName.setText(rowItem.getCinemaName());
}
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
holder.cinemaName.setText(rowItem.getCinemaName());
return convertView;
}
I'd create a method to update the adapter once an item on your spinner is chosen:
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
city = (String) parent.getItemAtPosition(position);
resetCinema(city); //or onRestart();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
And resetCinema(city) rechages the view depending on the city value. You can do this manually:
public void resetCinema(String city) {
//show list view elements depending on city
}
or just call a refresh of the whole Activity:
protected void onRestart() {
Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
}
I suggest you to call
adapter2.notifyDataSetChange();
But anyway there is no need to initialize a new adapter every time.
you should create a method inside the adapter like this:
public void setMyArray(ArrayList<Cinema> items) {
myArray.clear();
myArray.addAll(items);
notifyDataSetChange();
}
I have a custom list view, contains delete button and spinner (the spinner contain A-E characters).
And I have an issue with deleting the true row from my custom list view.
Custom list view code:
public class customListView extends BaseAdapter
{
public Activity context;
ArrayList<MyActivity.UserProperties> userPropertieses;
public String[] spinnerValues;
public LayoutInflater inflater;
public customListView(Activity context, ArrayList<MyActivity.UserProperties> userPropertieses, String[] spinnerArray)
{
super();
this.context = context;
this.userPropertieses = userPropertieses;
spinnerValues = spinnerArray;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() { return userPropertieses.size(); }
#Override
public Object getItem(int i) { return null; }
#Override
public long getItemId(int i) { return 0; }
class ViewHolder
{
Button btnRemove;
Spinner spinner;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup)
{
final ViewHolder holder;
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.custom_layout, null);
holder.spinner = (Spinner) view.findViewById(R.id.spinner);
holder.btnRemove = (Button) view.findViewById(R.id.bu_Remove);
// populate spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_item, spinnerValues);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setFocusable(true);
holder.spinner.requestFocus();
holder.spinner.setAdapter(dataAdapter);
view.setTag(holder);
// remove user implementation
holder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("custom list view debug", "i = " + i); // debug. verify i value is correct
((MyActivity) context).deleteUser(i);
}
});
}
else
holder = (ViewHolder) view.getTag();
return view;
}
}
And my main activity code looks like this:
public class MyActivity extends Activity
{
ListView listView;
ArrayList<UserProperties> userProperties = new ArrayList<UserProperties>();
customListView adapter;
SensorManager sensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
for (int i = 0; i<5; i++) {
userProperties.add(new UserProperties());
}
listView = (ListView) findViewById(R.id.listView);
String[] spinnerValues = new String[] {"A", "B", "C", "D", "E"};
adapter = new customListView(MyActivity.this, userProperties, spinnerValues);
listView.setAdapter(adapter);
}
public void deleteUser (int index)
{
Log.i("debug", "Removing item " + index); // the index is really true and the true node deleting from the ArrayList but somehow the latest delete from the UI
userProperties.remove(index);
adapter.notifyDataSetChanged();
}
}
When I click on the Remove button deleteUser method called with the right index. but although the right node deleting from userProperties ArrayList somehow after notiftDataSetChanged is still alive
and the latest node delete.
So, How can I delete the right node/row (from the ArrayList and UI...)
Thank you!
EDIT:
Just to be clear, i variable contain true index. The true node deleted from the ArrayList. but something append after I called notify method.
I prefer to stay with BaseAdapter and not implement ArrayAdapter. Thank you!
EDIT 2:
After more debugging I found out my question was wrong. the true row really deleted just spinner values somehow update their values. I cannot close the question because it already answered. Thanks.
((MyActivity) context).deleteUser(i);
This line will always delete the first value from the ListView
You can use CAB (contextual action bar)
See if the code helps you(it's basically a ListActivity with a custom adapter to hold the status of checked items(+ different background)):
public class CABSelection extends ListActivity {
private ArrayList<String> mItems = new ArrayList<String>();
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < 24; i++) {
mItems.add("Name" + i);
}
// R.layout.adapters_cabselection_row is a LinearLayout(with green
// background(#99cc00)) that wraps an ImageView and a TextView
mAdapter = new SelectionAdapter(this,
R.layout.adapters_cabselection_row, R.id.the_text, mItems);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cabselection_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
StringBuilder sb = new StringBuilder();
Set<Integer> positions = mAdapter.getCurrentCheckedPosition();
for (Integer pos : positions) {
sb.append(" " + pos + ",");
}
switch (item.getItemId()) {
case R.id.edit_entry:
Toast.makeText(CABSelection.this, "Edited entries: " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.delete_entry:
Toast.makeText(CABSelection.this, "Deleted entries : " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.finish_it:
nr = 0;
mAdapter.clearSelection();
Toast.makeText(CABSelection.this, "Finish the CAB!",
Toast.LENGTH_SHORT).show();
mode.finish();
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
nr = 0;
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " rows selected!");
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, !mAdapter.isPositionChecked(position));
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(Color.parseColor("#99cc00")); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(Color.RED);// this is a selected position so make it red
}
return v;
}
}
}
Another way
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
getView(final int i,
Do not make i final. You did that to use i in onClick(). But that is not possible. So remove the final. Add:
holder.btnRemove.setTag(i);
And in onClick:
int position = v.getTag();
..deleteUser(position);
Maybe you have to cast something somewhere..
Remark: You have to set the tag always. So do it just before return view;.
Please do not use an i for position.
This is my MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
ArrayList<Product> products = new ArrayList<Product>();
final Context context = this;
ListAdapter boxAdapter;
String[] dataArray;
EditText editText;
//name that get back through the dialog
private String getName;
private String selectedItem;
private ArrayAdapter<String> adapter; // The list adapter
/** Called when the activity is first created. */
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
fillData();
boxAdapter = new ListAdapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
Button btn = (Button) findViewById(R.id.AddItem);
//the add item button function
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//get the dialog view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.insert);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
getName=userInput.getText().toString();
products.add(new Product(getName,false));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
// Create the listener for normal item clicks
OnItemClickListener itemListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long rowid) {
Toast.makeText(
getApplicationContext(),
"You have clicked on " + parent.getItemAtPosition(position).toString() + ".",
Toast.LENGTH_SHORT).show();
}
};
//the long press to delete function
OnItemLongClickListener itemLongListener = new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to remove " + selectedItem + "?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
products.remove(selectedItem);
boxAdapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
}
void fillData() {
dataArray = getResources().getStringArray(R.array.ChecklistData);
for(String productName : dataArray)
{
products.add(new Product(productName,false));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
ListAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
/*((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);*/
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
OnItemClickListener and OnItemLongClickListener didn't function at all. Anyone help me out here.. I did diagnose the problem but it still doesn't have function
OnItemClickListener itemListener = new OnItemClickListener() {
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
You just define those variables but you don't assign them to your ListView.
You should call these lines somewhere:
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
UPDATE:
You also miss to register the list for context menu.
registerForContextMenu(lvMain);
implement View.OnItemClickListener and AdapterView.OnItemLongClickListener and their corresponding methods in your class.
initialize your views correctly (findViewById...)
set click listeners to your views (button.setOnClickListener(this) / button.setOnLongClickListener(this)
react to the push events in the implemented methods like:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
this.doSomething();
}
}
and
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//react to the view or react to the position
switch (view.getId()) {
case R.id.button:
this.doSomething();
}
return true;
}
You need to register listeners. Add following lines to the end of your onCreate() method.
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
I had the exact same problem. When onclick or onlongclick are enabled in the Layout; onitemclickListener wont work. Just remove the tags android:clickable and android:longclickable from your Layout XML resource and it will all work.
I want to make an app which includes a listView with check boxes and a two buttons named add and delete selected. I want to delete all the item that are checked in the list view.I am unable to do that despite of my lot of efforts. Any help would be appreciated.
Here is my code
package com.example.chkbokinlistview;
public class Adapter extends ArrayAdapter<Movies> {
ArrayList<Movies> data;
Context context;
int id;
private Holder h;
public Adapter(Context context, int textViewResourceId, ArrayList<Movies> objects) {
super(context, textViewResourceId, objects);
this.data = objects;
this.context = context;
this.id = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int p = position;
View v = convertView;
LayoutInflater l = ((Activity)context).getLayoutInflater();
h = new Holder();
if (v == null) {
v = l.inflate(id, parent, false);
h.tv = (TextView) v.findViewById(R.id.textView1);
h.cb = (CheckBox) v.findViewById(R.id.checkBox1);
v.setTag(h);
}else{
h = (Holder) v.getTag();
h.cb.setChecked(true);
}
h.tv.setText(data.get(position).movieName);
h.cb.setChecked(data.get(position).deleted);
return v;
}
public void delete(){
//how to delete all the items that are checked
}
class Holder{
TextView tv;
CheckBox cb;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
bDelete = (Button) findViewById(R.id.bDelete);
bAdd = (Button) findViewById(R.id.bAdd);
list = new ArrayList<Movies>();
a = new Adapter(this, R.layout.listitem, list);
lv.setAdapter(a);
bDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
a.delete();
}
});
bAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final EditText et = new EditText(MainActivity.this);
dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
list.add(new Movies(et.getText().toString(), false));
a.notifyDataSetChanged();
dialog.dismiss();
}
})
.setTitle("ADD Movie")
.setView(et)
.create();
dialog.show();
}
});
}
On checking the checkbox add that position in an ArrayList let say toBeDeleted, and when you click delete button, just remove items from your ArrayList named data according to the positions that you have in toBeDeleted and call the adapter method notifyDataSetChanged().
Add a checkedChangedListener in the getView method for your CheckBox.
h.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
// TODO Auto-generated method stub
if (arg1) {
list.add(position);
} else {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == position) {
list.remove(i);
break;
}
}
}
}
});
Where list is a ArrayList<Integer>,
and for deleting
private void delete() {
for(int i = 0 i<list.size;i++)
data.remove(list.get(i));
}
but before deleting you have to sort the list in decending order, in order to remove correctly, otherwise you may get an IndexOutofBoundException