I have a customlistadapter and i am setting it for my listview. Now I want to remove an item of it. I did something below in the longclick event but it returns and FATAL exception.
projectItemArrayAdapter is the object of my customAdapter class. item is the position of the list.
Object item1 = projectItemArrayAdapter.getItem(item);
projectItemArrayAdapter.remove(item1);
projectItemArrayAdapter.notifyDataSetChanged();
LogCat
09-01 16:07:39.564 3506-3506/com.example.anuradha.tblogin
E/AndroidRuntime﹕ FATAL EXCEPTION: main Process:
com.example.anuradha.tblogin, PID: 3506
java.lang.UnsupportedOperationException at
java.util.AbstractList.remove(AbstractList.java:638) at
java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
at java.util.AbstractCollection.remove(AbstractCollection.java:229)
ProjectAdapter class
public class ProjectAdapter extends ArrayAdapter {
private final Context context;
private final String[] values;
private final String[] titles;
private LayoutInflater inflater;
public ProjectAdapter(Context activity,String[] values,String[] titles)
{
super(activity,R.layout.activity_project_item,values);
//inflater = activity.getWindow().getLayoutInflater();
this.context = activity;
this.values = values;
this.titles = titles;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return inflater.inflate(R.layout.activity_project_item,parent,false);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_project_item, parent, false);
TextView project = (TextView) rowView.findViewById(R.id.projectName);
TextView title = (TextView) rowView.findViewById(R.id.projectTitle);
project.setText(values[position]);
title.setText(titles[position]);
if (position%2!=1)
{
String myHexColor = "#2d07101c";
//project.setBackgroundColor(Color.parseColor(myHexColor));
rowView.setBackgroundColor(Color.parseColor(myHexColor));
}
return rowView;
}
#Override
public void remove(Object object) {
super.remove(object);
}
}
ProjectList class - I assign arrayadapter to my listview
public class ProjectList extends Activity {
private ListView projectListView;
private String[] stringArray ;
private ArrayAdapter projectItemArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_list);
//Set custom ActionBar Color
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#D6D6D6")));
String[] projectName =
new String[] { "Demo", "Test", "Anu", "QDMS"};
String[] projTitle =
new String[] { "Demo Title", "Test Title", "Anu Title", "QDMS Title"};
projectItemArrayAdapter = new ProjectAdapter(this,projectName,projTitle);
projectListView = (ListView) findViewById(R.id.projectList);
projectListView.setAdapter(projectItemArrayAdapter);
this.showActionBar();
projectListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ProjectList.this,MailActiivty.class);
startActivity(intent);
}
});
projectListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long arg3) {
final int item = position;
AlertDialog.Builder alert = new AlertDialog.Builder(
ProjectList.this);
alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Object item1 = projectItemArrayAdapter.getItemId(item);
projectItemArrayAdapter.remove(item1);
projectItemArrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("CANCEL",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alert.show();
return true;
}
});
}
//method to assign custom actionbar
private void showActionBar() {
LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.cust_actionbar, null);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled (false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setCustomView(v);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_project_list, menu);
return super.onCreateOptionsMenu(menu);
}
#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);
}
}
Use ArrayList instead of an array. Change the adapter constructor to this.
public ProjectAdapter(Context activity,List<String> values,String[] titles)
{
super(activity,R.layout.activity_project_item,values);
//inflater = activity.getWindow().getLayoutInflater();
this.context = activity;
//change the type of values from String[] to List<String>
this.values = values;
this.titles = titles;
}
Then change implementation of remove method. It should look like this
#Override
public void remove(Object object)
{
//remove the call to super.
values.remove(object);
}
Then change this line
String[] projectName = new String[] { "Demo", "Test", "Anu", "QDMS"};
Create an array list and add these elements to it and then pass the list to the adapter constructor.
Let me know if it works. Cheers :)
Related
I'm quite new at Android developing and I was trying to put a a context menu on my Listview that uses a CursorAdapter, I followed this examples https://www.youtube.com/watch?v=Pq9YQl0nfEk Using contextmenu with listview in android but the menu doesn't appear and I don't no why, appearently everything's OK.
These is the code of my activity
public class ProductsView extends AppCompatActivity {
private FloatingActionButton botonAnadir;
private ListView lvProducts;
SetOfProductList mylist;
private ProductAdapter productAdapter;
Cursor cursor;
private ProductList productList;
private Long idProductList;
private DBManager dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
productList = bundle.getParcelable("productList");
setTitle(getResources().getString(R.string.show_products) + " " + productList.getName());
}
setContentView(R.layout.products_view);
initialize();
}
private void initialize(){
botonAnadir = (FloatingActionButton)findViewById(R.id.button_add_product);
lvProducts = (ListView)findViewById(R.id.listViewProducts);
dbManager = new DBManager(getApplicationContext());
loadProducts();
registerForContextMenu(lvProducts);
botonAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
creaNuevaLista();
}
});
lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product aux = getProduct(position);
goToNewProduct(aux);
}
});
lvProducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// markAsPurchased(position);
return true;
}
});
}
private void markAsPurchased(int position){
Product p = getProduct(position);
TextView item = (TextView) findViewById(R.id.textview_product_name);
if (p.getPurchased() == 0){
p.setPurchased(1); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
p.setPurchased(0); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
editProduct(p); //makes de update
loadProducts();
}
private void editProduct(Product product){
dbManager.updateProduct(product);
}
private void goToNewProduct(Product p){
Intent intent = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putBoolean("editMode",true);
b.putParcelable("product", p);
intent.putExtras(b);
startActivity(intent);
}
private void creaNuevaLista(){
Intent i = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putParcelable("productList", productList);
i.putExtras(b);
startActivityForResult(i, 0);
}
private void loadProducts(){
cursor = dbManager.getAllProductsWithCursor(productList);
productAdapter = new ProductAdapter(this,cursor);
lvProducts.setAdapter(productAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listViewProducts){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.prodcut_view_context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()){
case R.id.delete_id:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
And this is the adapter that I'm using
public class ProductAdapter extends CursorAdapter {
private LayoutInflater inflater;
//Constructor
public ProductAdapter(Context context, Cursor cursor) {
super(context, cursor,false);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_product_row,parent,false);
return view;
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv_product_name = (TextView) view.findViewById(R.id.textview_product_name); // Find fields to populate in inflated template
String product_name = cursor.getString(cursor.getColumnIndexOrThrow("name"));// Extract properties from cursor
// Populate fields with extracted properties
tv_product_name.setText(product_name);
if (cursor.getInt(cursor.getColumnIndexOrThrow("purchased")) == 1){
tv_product_name.setPaintFlags(tv_product_name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
public Product getProduct(int position, Cursor cursor) {
Product p=null;
if(cursor.moveToPosition(position)) {
Log.e("PRODUCTLISTADAPTER","nombre es: "+cursor.getString(cursor.getColumnIndex("name")));
p = new Product (cursor.getLong(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("unit_type")),cursor.getDouble(cursor.getColumnIndex("value")),cursor.getInt(cursor.getColumnIndex("purchased")),cursor.getLong(cursor.getColumnIndex("id_pl")));
}
return p;
}
}
Can anyone exaplin me why it isn't working? isn't it necessary to make something on the LongClickListener ? because I don't see that the menu is being created.
Thanks in advance.
You've set an OnItemLongClickListener for the ListView, which will run before the context Menu is created. Returning true from its onItemLongClick() method indicates that the long click is being consumed there, so the Menu will not be created.
If you don't actually need the OnItemLongClickListener, you can remove the relevant code. If you do need it as well, for some reason, you can return false from onItemLongClick(), and your Menu will then show.
i need help to save the rating of rating bar in my list view for each item.My question is how can i do it because the OnItemClickListener does not work.
this is how my custom array adapter looks like
public class CustomArrayAdapter extends ArrayAdapter<String> {
public ArrayList<String> ratings;
private Activity context;
private int[] imageID;
private String[] stdName;
private double[] GPA;
private String[] course;
private String[] rollNo;
public float cRating;
public CustomArrayAdapter(Activity context, int[] imageID, String[] stdName, double[] GPA, String[] course, String[] rollNo) {
super(context, R.layout.row_design, stdName);
this.context = context;
this.imageID = imageID;
this.stdName = stdName;
this.GPA = GPA;
this.course = course;
this.rollNo = rollNo;
}
static class ViewContainer
{
public ImageView stdImage;
public ImageView possibleImage;
public TextView primaryTV;
public TextView secondryTV;
public RatingBar ratingBar;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = convertView;
if(rowView == null) {
//converting the XML file into view objects
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.row_design, null, true);
viewContainer = new ViewContainer();
//getting the refrence of widgets
viewContainer.stdImage = (ImageView) rowView.findViewById(R.id.student_image);
viewContainer.possibleImage = (ImageView) rowView.findViewById(R.id.possibility_image);
viewContainer.primaryTV = (TextView) rowView.findViewById(R.id.primary_text_view);
viewContainer.secondryTV = (TextView) rowView.findViewById(R.id.secondry_text_view);
viewContainer.ratingBar = (RatingBar) rowView.findViewById(R.id.rating_bar);
rowView.setTag(viewContainer);
} else {
viewContainer = (ViewContainer) rowView.getTag();
viewContainer.ratingBar.setRating(0.0f);
rowView.setBackground(null);
}
viewContainer.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
cRating = rating;
}
});
//setting the possible values to widgets
viewContainer.stdImage.setImageResource(imageID[position]);
viewContainer.primaryTV.setText(stdName[position] + " (GPA:" + GPA[position] + ")");
viewContainer.secondryTV.setText(course[position] + " (RollNo:" + rollNo[position] + ")");
if (GPA[position] < 3.0) {
rowView.setBackgroundResource(android.R.color.holo_red_light);
viewContainer.possibleImage.setImageResource(R.drawable.cross_small);
} else {
viewContainer.possibleImage.setImageResource(R.drawable.tick_small);
}
return rowView;
}
}
and this is my activity where i want to get the rating
public class StudentSelectionActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_selection);
//getting the refrence of list view
ListView listView = (ListView) findViewById(R.id.list);
//creating object of Rating activity to access it's public instances
final MainActivity obj = new MainActivity();
//creating custom adapter
final CustomArrayAdapter adapter = new CustomArrayAdapter(this, obj.imageID, obj.stdName, obj.GPA, obj.course, obj.rollNo);
listView.setAdapter(adapter);
//handling events on click listener of list view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(StudentSelectionActivity.this, "rating = " + adapter.cRating, Toast.LENGTH_SHORT).show();
}
});
}
#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_selected_students, 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);
}
}
Your setOnItemClickListener did not work for adapter class as you are using another clickable class inside adapter. So one option is to use click listener inside adapter class.
As
rowView.setOnClickListener(new View.onClickListener()
{
//Perform your operation.
});
Create an Entry class. This class holds your attributes, like cRating.
Then extend the CustomArrayAdapter for ArrayAdapter<Entry> instead of ArrayAdapter<String>. Change the constructor to something like this
public CustomArrayAdapter(Context context, int layoutResourceID, List<Entry> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.itemList = listItems;
this.layoutResID = layoutResourceID;
}
In your getView method use
EventDetailEntry item = this.itemList.get(position);
to get the corresponding item. Use this item to set the cRating. Then your onItemClicked method should work as expected. Hope that is clear enough.
So i'm trying to make a searchable list view using a custom array adapter.
I finally got the search working but the results are not exactly accurate.
Its actually a hit and miss kinda thing e.g Searching for Drupal gets me Google Plus, you knw what I saying?
So here's my adapter
public class CustomListAdapter extends ArrayAdapter<String> implements Filterable {
private final Activity context;
private final String[] web;
private final String[] imageIdUrl;
public CustomListAdapter(Activity context, String[] web, String[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageIdUrl = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
//find row view
View rowView= inflater.inflate(R.layout.list_single, null, true);
//find text
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
//find image
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
//set text
txtTitle.setText(web[position]);
//set image traditional
//imageView.setImageResource(imageIdUrl[position]);
//set image with picasso
Picasso.with(this.context).load(imageIdUrl[position]).into(imageView);
//return row
return rowView;
}
}
And heres my Main Activity class
public class MainActivity extends ActionBarActivity {
ListView list;
EditText editsearch;
String[] web = {
"Google Plus",
"Twitter",
"Windows",
"Bing",
"Itunes",
"Wordpress",
"Drupal"} ;
String[] imageIdUrl = {
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg",
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg" ,
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg",
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg",
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg",
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg",
"http://www.h3dwallpapers.com/wp-content/uploads/2015/05/Google_Logo_04.jpg"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, web, imageIdUrl);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + web[+position], Toast.LENGTH_SHORT).show();
}
});
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.editText);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.getFilter().filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#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_main, 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);
}
}
I'll be grately thankful for any help. This is proving to be a major headache
Change the code in onTextChanged() method to afterTextChanged() method as below:
#Override
public void afterTextChanged(Editable s) {
String str=s.toString();
getSearchItems(str);
}
In getSearchItems use the filter properly. I used other way to filter as,
public void getSearchItems(String searchText){
List<Employee> searchList=new ArrayList<Employee>();
List<Employee> employeeList=getEmployeeList();
if(employeeList2!=null){
for(Employee e:employeeList){
if(e.name.toLowerCase().contains(searchText.toLowerCase())){
searchList.add(e);
}
}
}
adapter.refresh(searchList);
}
Then In adapter use another method refresh() as below:
public void refresh(List<Employee> employeeList){
this.employeeList=employeeList;
notifyDataSetChanged();
}
Actually I used Employee class which contains his name and address, and I made search using employee name. So u change the above code which suits your search.
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.
I am using slidemenu example from github and it's showing slide menu only with text and header but I need to add different icon with it. I am trying to use a custom adapter but it's not working...
slidemenu.java:
public class SlideMenu implements SlideMenuAnimationContainer.Listener {
public final static String[] slideMenuOptions = { "Recent Update", "Notification", "Wardrobe" };
public final static String TAG = "SlideMenu";
protected static final String TextView = null;
Intent intent;
private Context context;
private SlideMenuAnimationContainer slideMenuAnimationContainer;
public SlideMenu( Context context, SlideMenuAnimationContainer mainAnimationLayout){
this.context = context;
this.slideMenuAnimationContainer = mainAnimationLayout;
}
public void init(){
final Activity activity = (Activity) context;
//Set Content's show menu button's action
ImageView showMenuButton = (ImageView) activity.findViewById( R.id.content_button);
showMenuButton.setOnClickListener( new OnClickListener(){
#Override
public void onClick( View v){
slideMenuAnimationContainer.toggleSlideMenu();
}
});
//Contruct the SlideMenu items here, you can replace this ArrayAdapter with your customr ArrayAdapter
List<SlideMenuItem> slideMenuList = new ArrayList<SlideMenuItem>();
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Updates"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Recent Update"));
// slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Header 2"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Notification"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Category"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Wardrobe"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Gadgets"));
SlideMenuArrayAdapter slideMenuArrayAdaptar = new SlideMenuArrayAdapter( context, android.R.layout.simple_list_item_1, slideMenuList);
ListView menuListView = (ListView) activity.findViewById( R.id.slideMenuListView);
menuListView.setAdapter( slideMenuArrayAdaptar);
menuListView.setOnItemClickListener( new OnItemClickListener(){
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id){
// Close sidebar
slideMenuAnimationContainer.closeSlideMenuAndActOnClick( parent, view, position, id);
}
});
//Implement your logic here within the execute() function when an item is clicked with in the SlideMenu
//Called after the SlideMenu collapses.
slideMenuAnimationContainer.setMenuItemSelectedAction( new MenuItemSelectedAction(){
#Override
public void execute( AdapterView<?> parent, View view, int position, long id){
//Only act when a ListViewItem with type Activity is clicked
TextView textView = (TextView)view.findViewById( R.id.MenuActivityListViewItem_text);
if( textView != null && textView.getId() == R.id.MenuActivityListViewItem_text){
//Start new activity
CharSequence selectedActivityName = textView.getText();
if( selectedActivityName.equals( "Recent Update")) {
intent = new Intent( activity, Activity1.class);
}
else if( selectedActivityName.equals( "Notification")) {
intent = new Intent( activity, Activity2.class);
}
else if( selectedActivityName.equals( "Wardrobe")) {
intent = new Intent( activity, Activity3.class);
}
else if( selectedActivityName.equals( "Gadgets")) {
intent = new Intent( activity, Gadgets_Activity.class);
}
intent =intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.startActivity( intent);
}
}
});
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuOpened(){
Log.d( TAG, "opened");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuClosed(){
Log.d( TAG, "closed");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public boolean onContentTouchedWhenOpening(){
//The content area is touched when sidebar opening, close sidebar
Log.d( TAG, "going to close sidebar");
slideMenuAnimationContainer.closeSlideMenu();
return true;
}
}
and Adapter:
public class SlideMenuArrayAdapter extends ArrayAdapter<SlideMenuItem> {
private List<SlideMenuItem> slideMenuItemList;
public SlideMenuArrayAdapter( Context context, int textViewResourceId, List<SlideMenuItem> slideMenuItemList) {
super( context, textViewResourceId, slideMenuItemList);
this.slideMenuItemList = slideMenuItemList;
}
#Override
public View getView( int position, View view, ViewGroup parent) {
SlideMenuItem slideMenuItem = slideMenuItemList.get( position);
LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Header){
view = layoutInflater.inflate( R.layout.menu_header_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuListHeaderListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Activity){
view = layoutInflater.inflate( R.layout.menu_activity_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuActivityListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else{
view = null; //Left for operation
}
return view;
}
}
Try like this
ListView listView = (ListView) menu.findViewById(R.id.list);
ArrayList<String[]> datavalues=new ArrayList<String[]>();
String[] menuhome=new String[2];
menuhome[0]=""+R.drawable.home_sidebar;
menuhome[1]="Home";
datavalues.add(menuhome);
String[] menuprofile=new String[2];
menuprofile[0]=""+R.drawable.profile_sidebar;
menuprofile[1]="Profile";
datavalues.add(menuprofile);
String[] menusearch=new String[2];
menusearch[0]=""+R.drawable.search_sidebar;
menusearch[1]="Search";
datavalues.add(menusearch);
String[] menugallery=new String[2];
menugallery[0]=""+R.drawable.gallery_sidebar;
menugallery[1]="Gallery";
datavalues.add(menugallery);
String[] menulogout=new String[2];
menulogout[0]=""+R.drawable.logout_sidebar;
menulogout[1]="Logout";
datavalues.add(menulogout);
SlideMenuAdapter menuadapter=new SlideMenuAdapter(datavalues, this);
listView.setAdapter(menuadapter);
private class SlideMenuAdapter extends BaseAdapter{
ArrayList<String[]> data;
ActivityListing context;
public SlideMenuAdapter(ArrayList<String[]> datavalues,
ActivityListing contextobj) {
// TODO Auto-generated constructor stub
data=datavalues;
context=contextobj;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
final int pos=arg0;
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.menurow, null, false);
int drawable=Integer.parseInt(data.get(arg0)[0].trim());
Button btnOption=(Button) convertView.findViewById(R.id.btnoption);
btnOption.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(drawable), null, null, null);
btnOption.setText(data.get(arg0)[1].trim());
btnOption.setTextColor(Color.rgb(143, 7, 0));
btnOption.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
callOptions(data.get(pos));
}
});
return convertView;
}