i want the same as this link https://www.gorecess.com/ first spinner . multi selection spinner in android with checkbox .Show the spinner in dropdown. anyone know answer...
multi select spinner :
1- create a spinner in your own xml ,like this
<Spinner
android:id="#+id/mySpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="1dp"/>
2-create a custom dapter for spinner like this :
public class AdapterTagSpinnerItem extends ArrayAdapter<TagListSimpleSearch>
{
private LayoutInflater mInflater;
private List<TagListSimpleSearch> listState;
public Spinner mySpinner = null;
public AdapterTagSpinnerItem(Context context, int resource, List<TagListSimpleSearch> objects, Spinner mySpinner)
{
super(context, resource, objects);
this.listState = objects;
this.mySpinner = mySpinner;
mInflater = LayoutInflater.from(context);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView, ViewGroup parent)
{
String text = "";
final ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.spinner_item, null, false);
holder.mTextView = convertView.findViewById(R.id.tvSpinnerItem);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
/**
* check position , if position is zero we put space on top of list of spinner
*/
if ((position == 0))
text = oneSpace;
/**
* check position , if position is one we put cross mark before text to show that position used to be for clear all selected items on spinner
*/
else if ((position == 1))
text = " " + String.valueOf((char) crossMarkAroundBox) + " " + listState.get(position).getTagText();
/**
* check position , if position is two we put check mark before text to show that position used to be for select all items on spinner
*/
else if ((position == 2))
text = " " + String.valueOf((char) tikMarkAroundBox) + " " + listState.get(position).getTagText();
/**
* check position , if position is bigger than two we have to check that position is selected before or not and put check mark or dash before text
*/
else
{
if (listState.get(position).isSelected())
{
text = " " + String.valueOf((char) tikMark) + " " + listState.get(position).getTagText();
}
else
{
text = " " + String.valueOf(dash) + " " + listState.get(position).getTagText();
}
}
holder.mTextView.setText(text);
holder.mTextView.setTag(position);
holder.mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/**
* if you want open spinner after click on text for first time we have to open spinner programmatically
*/
mySpinner.performClick();
int getPosition = (Integer) v.getTag();
listState.get(getPosition).setSelected(!listState.get(getPosition).isSelected());
notifyDataSetChanged();
/**
* if clicked position is one
* that means you want clear all select item in list
*/
if (getPosition == 1)
{
clearList();
}
/**
* if clicked position is two
* that means you want select all item in list
*/
else if (getPosition == 2)
{
fillList();
}
}
});
return convertView;
}
/**
* clear all items in list
*/
public void clearList()
{
for (TagListSimpleSearch items : listState)
{
items.setSelected(false);
}
notifyDataSetChanged();
}
/**
* select all items in list
*/
public void fillList()
{
for (TagListSimpleSearch items : listState)
{
items.setSelected(true);
}
notifyDataSetChanged();
}
/**
* view holder
*/
private class ViewHolder
{
private TextView mTextView;
}
}
3- now you have to create object for adapter
public class TagListSimpleSearch {
private String TagId;
private String TagText;
private boolean selected;
public String getTagId() {
return TagId;
}
public void setTagId(String TagId) {
this.TagId = TagId;
}
public String getTagText() {
return TagText;
}
public void setTagText(String tagText) {
TagText = tagText;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
}
4-fill spinner adapter in your activity
public static String oneSpace =" ";
public static int tikMark =0X2714;
public static int crossMark =0X2715;
public static int tikMarkAroundBox =0X2611;
public static int crossMarkAroundBox =0X274E;
public static String dash ="-";
private Spinner mySpinner;
mySpinner= (Spinner) findViewById(R.id.mySpinner);
List<TagListSimpleSearch> tagsNames = new ArrayList<>();
TagListSimpleSearch tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText(oneSpace);
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("select All Items");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("remove All Items");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("0");
tagSpecific.setTagText("Item 0");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("1");
tagSpecific.setTagText("Item 1");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("2");
tagSpecific.setTagText("Item 2");
tagsNames.add(tagSpecific);
tagSpecific=new TagListSimpleSearch();
tagSpecific.setTagId("3");
tagSpecific.setTagText("Item 3");
tagsNames.add(tagSpecific);
final AdapterTagSpinnerItem adapterTagSpinnerItem = new AdapterTagSpinnerItem(this, 0, tagsNames,mySpinner);
mySpinner.setAdapter(adapterTagSpinnerItem);
<com.extra.MultiSelectionSpinner
android:id="#+id/input1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp" />
MultiSelectionSpinner spinner=(MultiSelectionSpinner)findViewById(R.id.input1);
List<String> list = new ArrayList<String>();
list.add("List1");
list.add("List2");
spinner.setItems(list);
I have implemented a multiple selection spinner in android using AlertDialog
check the following code
public void classesSelect(){
regclassvalue.setText("");
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setTitle("Select Services");
final int array[] = new int[serarray.length];
check = new boolean[serarray.length];
for (int k = 0; k < serarray.length; k++) {
check[k] = false;
}
final List<String> classlist = Arrays.asList(serarray);
final List<Integer> classidlist = Arrays.asList(classidarray);
// this is the main part here we set the multichoice listener using serarray and check
builder.setMultiChoiceItems(serarray, check, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
check[which] = isChecked;
}
});
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
regclassvalue.setText("");
classids = "";
int io = 0;
for (int ii = 0; ii < check.length; ii++) {
boolean checked = check[ii];
if (checked) {
array[io] = ii;
io++;
}
}
for (int k = 0; k < io; k++) {
if (io == 1) {
classids = classids + classidlist.get(array[k]);
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]));
} else if (k == io - 1) {
classids = classids + classidlist.get(array[k]);
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]));
} else {
classids = classids + classidlist.get(array[k]) + ",";
regclassvalue.setText(regclassvalue.getText() + classlist.get(array[k]) + " ,");
}
}
//Toast.makeText(RegisterActivity.this,classids,Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
for more info please click here
Related
I face a problem in list view. In my list view have edit text and text view. When i scroll the list my data that is entered in text view has lost the value and show the default value. i have two button in list view i increase the quantity and scroll the list for next product when i come back text view lost the value and show default value 1 . And when i open keyboard for enter data then same issue . please help me.
And its my code
Custom Adapter
private List<ShowProducts> listShowProducts;
private Context context;
private int resource;
private String condition;
String uri;
private static final String TAG = "CustomAdapter";
int i = 0;
float total;
ListView listView;
TextView tvTotal;
float sum = 0;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, List<ShowProducts> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.listShowProducts = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Nullable
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(resource, parent, false);
{
final ShowProducts showProducts = listShowProducts.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageViewOfSelecteditem);
ImageView plus = (ImageView) view.findViewById(R.id.imageviewPlus);
ImageView minus = (ImageView) view.findViewById(R.id.imageviewminus);
TextView tvSetNameOfSeletedItem = (TextView) view.findViewById(R.id.tvSetNameOfSeletedItem);
TextView tvSetSizeOfSeletedItem = (TextView) view.findViewById(R.id.tvSetSizeOfSeletedItem);
TextView tvSetPriceOfSeletedItem = (TextView) view.findViewById(R.id.tvSetPriceOfSeletedItem);
final TextView tvQunatitySetOfSelectedItem = (TextView) view.findViewById(R.id.tvQunatitySetOfSelectedItem);
for (int a = 0; a < 10; a++) {
Log.d(TAG, "onnnnView: ");
}
Log.d(TAG, "getView: +++++");
tvSetNameOfSeletedItem.setText(showProducts.getProduct_name().toString());
tvSetSizeOfSeletedItem.setText(showProducts.getSize_name());
tvSetPriceOfSeletedItem.setText(String.valueOf(showProducts.getSize_price()).toString());
uri = showProducts.getProduct_photo().toString();
Picasso.with(context).load(uri).into(imageView);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
Log.d(TAG, "getView: ");
if (a <= showProducts.getSize_quantity()) {
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a--;
if (a > 0)
{
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price - showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
}
return view;
}
And activity code
public class SelectedProductFromShopingCartShow extends AppCompatActivity {
ArrayList<ShowProducts> arrayList = new ArrayList<>();
String condition = "SelectedItemsFromShoppingCart";
CustomAdapter customAdapter;
ListView listView;
TextView tvTotal;
EditText etDiscount;
int total;
float sum = 0;
Button discount;
private static final String TAG = "SelectedProductFromShop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
listView = (ListView) findViewById(R.id.listViewSelectedItemsOfShopingCart);
tvTotal = (TextView) findViewById(R.id.tvTotalShow);
etDiscount = (EditText) findViewById(R.id.etDiscount);
arrayList = (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
ShowProducts showProducts = arrayList.get(0);
Log.d(TAG, "onnnnCreate: " + showProducts.getProduct_name());
customAdapter = new CustomAdapter(SelectedProductFromShopingCartShow.this, R.layout.show_selected_item_of_shopingcart, condition, arrayList);
listView.setAdapter(customAdapter);
getTotalListView();
Log.d(TAG, "onnnnCreate: Before inner class");
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(SelectedProductFromShopingCartShow.this);
builder.setTitle("Delete this product");
builder.setMessage("Are you sure you want to delete it?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
customAdapter.notifyDataSetChanged();
Toast.makeText(SelectedProductFromShopingCartShow.this, "item deleted", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.show();
return true;
}
});
}
public void getTotalListView() {
sum = 0;
for (int i = 0; i < arrayList.size(); i++) {
ShowProducts showProducts = arrayList.get(i);
sum = sum + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
And watch this video for understand problems
https://youtu.be/WAjtRkI5dl4
You need to follow viewholder pattern. It will resolve your issue. You can check it here https://developer.android.com/training/improving-layouts/smooth-scrolling.html
The only place you're keeping count is in the view. You should make your count a field in the list item ShowProducts and create a getter & setter. For example, in the plus onClickListener, instead of
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
You'll have
// for example, in the `plus` listener
int a = showProducts.getCount();
a++;
showProducts.setCount(a);
And don't forget
notifyDataSetChanged();
In Activity WorkDetailsTable , it has a ListView as shown below. When it is clicked, it should display the value on the Add_Details_Information EditText
Assume the first list is clicked, and it intent to Add_Details_Information
Noted that the value on editText was actually get from the second list in Activity A. But what I want is get value accordingly to their position not the latest value.
WorkDetailsTable
int mClickedPosition;
MyCustomBaseAdapter objMyCustomBaseAdapter;
ArrayList<SearchResults> results=new ArrayList<SearchResults>();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
// how to getPosition???
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveProject", ReceiveProject);
i.putExtra("ReceiveDescription", ReceiveDescription);
i.putExtra("ReceiveProgress", ReceiveProgress);
i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
i.putExtra("date",date);
i.putExtra("status", status);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
Add_Details_Information
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_details_information);
addItemsOnSpinner(); // Spinner for project/service/training
tp = new TimePick(); // call tmePick
description=(EditText)findViewById(R.id.editTextWorkDescription);
timeIn=(EditText)findViewById(R.id.TimeIn);
timeOut=(EditText)findViewById(R.id.TimeOut);
save=(Button)findViewById(R.id.saveButton);
seekBar=(SeekBar)findViewById(R.id.seekBarPercentage);
progressText=(TextView)findViewById(R.id.textProgress);
progressText.setText("Covered:" + "" + seekBar.getProgress() + "/" + seekBar.getMax());
if(getIntent().getExtras()!=null)
{
final String Project1=getIntent().getStringExtra("ReceiveProject");
final String Description1=getIntent().getStringExtra("ReceiveDescription");
final int Progress1=getIntent().getIntExtra("ReceiveProgress", 0);
final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
// project.setText(Project1);
description.setText(Description1);
seekBar.setProgress(Progress1);
timeIn.setText(TimeIn1);
timeOut.setText(TimeOut1);
seekBar.setProgress(Progress1);
progressText.setText("Covered:" + "" + seekBar.getProgress() + "/" + seekBar.getMax());
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView in WorkDetailsTable
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public void addNewItem(String P,String D,int Per,String I,String O)
{
SearchResults obj=new SearchResults();
obj.setProject(" Project/Service/Training : "+P);
obj.setDescription(" Work Description : " + D);
obj.setProgress(" Progress : " + Per);
obj.setTimeIn(" Time In : " + I);
obj.setTimeOut(" Time Out : " + O);
searchArrayList.add(obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
holder.txtProgress = (TextView) convertView.findViewById(R.id.ListProgress);
holder.txtIn=(TextView)convertView.findViewById(R.id.ListTimeIn);
holder.txtOut=(TextView)convertView.findViewById(R.id.ListTimeOut);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
holder.txtProgress.setText(searchArrayList.get(position).getProgress());
holder.txtIn.setText(searchArrayList.get(position).getTimeIn());
holder.txtOut.setText(searchArrayList.get(position).getTimeOut());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
TextView txtProgress;
TextView txtIn;
TextView txtOut;
}
}
Trying Code
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o=listview.getItemAtPosition(position);
SearchResults fullObject=(SearchResults)o;
String ReceiveDescription=((SearchResults) o).getDescription();
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveDescription", ReceiveDescription);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
Try this:
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
I download data from server and fill the listview with them. Every item in the listview has 3 buttons, on every button I would like to make an onclicklistener. When the user clicks one of the buttons, It should for example open the new activity. Every row (object) has some id, and when I click on some of these buttons, the id is always for example 15 (it is always the id of the last row in listview).
I have tried to declare the OnClickListeners with many different ways, the result was the same.
LawsAdapter
public class LawsAdapter extends ArrayAdapter<Law> implements View.OnClickListener {
private LayoutInflater inflater;
private Context context;
private UserLocalStore userLocalStore;
private IsVotedStorage isVotedStorage;
private View convertView;
private ViewHolder viewHolder;
/**
* Constructor, declares storages, context and inflater
* #param context
* #param textViewResourceId
*/
public LawsAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.context = context;
inflater = ((Activity) context).getLayoutInflater();
userLocalStore = new UserLocalStore(context);
isVotedStorage = new IsVotedStorage(context);
}
/**
* Second constructor, here you can set the resource (againstr the previous one)
* #param context
* #param resource
* #param items
*/
public LawsAdapter(Context context, int resource, List<Law> items) {
super(context, resource, items);
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
userLocalStore = new UserLocalStore(context);
isVotedStorage = new IsVotedStorage(context);
}
/**
* Overriden method getView, declares graphic objects (btns... ) and set listeners
* #param position
* #param convertView
* #param parent
* #return view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.law_item, parent, false);
this.convertView = convertView;
viewHolder = new ViewHolder();
viewHolder.tvName = (TextView) convertView.findViewById(R.id.lawItemName);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.lawItemDescription);
viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.lawItemStatus);
viewHolder.btnDownvote = (Button) convertView.findViewById(R.id.lawItemDownvote);
viewHolder.btnUpvote = (Button) convertView.findViewById(R.id.lawItemUpvote);
viewHolder.btnMakeComment = (Button) convertView.findViewById(R.id.lawItemMakeComment);
viewHolder.currentLaw = getItem(position);
Log.d("View holder", "new one");
Log.d("LAW ID, ADAPTER", String.valueOf(viewHolder.currentLaw.getId()));
viewHolder.tvName.setText(viewHolder.currentLaw.getName());
viewHolder.tvDescription.setText(viewHolder.currentLaw.getDescription());
viewHolder.tvStatus.setText(viewHolder.currentLaw.getStateValue());
setSurfacesColors();
viewHolder.btnMakeComment.setOnClickListener(this);
viewHolder.btnDownvote.setOnClickListener(this);
viewHolder.btnUpvote.setOnClickListener(this);
disableIfVoted();
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
Log.d("View holder", "get tag");
}
return convertView;
}
/**
* Set the colors of surfaces
*/
private void setSurfacesColors() {
viewHolder.sfLeft = (SurfaceView) convertView.findViewById(R.id.lawItemSurfaceLeft);
viewHolder.sfBackground = (SurfaceView) convertView.findViewById(R.id.lawItemSurfaceBackground);
Log.d("VOTES", "Positive: " + viewHolder.currentLaw.getPositiveVotes() + " Negative: " + viewHolder.currentLaw.getNegativeVotes());
if ((viewHolder.currentLaw.getNegativePercent() + viewHolder.currentLaw.getNegativeVotes()) > 1) {
viewHolder.sfBackground.setBackgroundColor(context.getResources().getColor(R.color.redSurfaceBckg));
viewHolder.sfLeft.setBackgroundColor(context.getResources().getColor(R.color.btnSubmitColor));
int screenWidth = getScreenWidth();
int upvote = viewHolder.currentLaw.getNegativePercent();
int downvote = viewHolder.currentLaw.getPositivePercent();
int positivePixels = (screenWidth / 100) * upvote;
int negativePixels = (screenWidth / 100) * downvote;
viewHolder.sfBackground.getHolder().setFixedSize(negativePixels, 5);
viewHolder.sfLeft.getHolder().setFixedSize(positivePixels, 5);
Log.d("UPDATE", "NOTIFY");
}
else {
viewHolder.sfBackground.setBackgroundColor(context.getResources().getColor(R.color.greySurface));
viewHolder.sfLeft.setBackgroundColor(context.getResources().getColor(R.color.greySurface));
}
}
/**
* Upvote
* #param law
*/
private void upvote(Law law) {
ServerRequest serverRequest = new ServerRequest(context);
serverRequest.upvoteLawInBackground(law.getId(), new UpDownCallback() {
#Override
public void done(Law law) {
viewHolder.currentLaw = law;
setSurfacesColors();
Log.e("VOTES in UPVOTE", "Positive: " + viewHolder.currentLaw.getPositiveVotes() + " Negative: " + viewHolder.currentLaw.getNegativeVotes());
}
});
}
/**
* Downvote
* #param law
*/
private void downvote(Law law) {
ServerRequest serverRequest = new ServerRequest(context);
serverRequest.downvoteLawInBackground(law.getId(), new UpDownCallback() {
#Override
public void done(Law law) {
viewHolder.currentLaw = law;
setSurfacesColors();
}
});
}
/**
* Get screen width in pixels
* #return int screen width
*/
private int getScreenWidth() {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
return width;
}
/**
* Disable voting button if I have already voted
*/
private void disableIfVoted() {
if (isVotedStorage.isVoted(viewHolder.currentLaw.getId())) {
viewHolder.btnUpvote.setEnabled(false);
viewHolder.btnDownvote.setEnabled(false);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lawItemMakeComment:
if (userLocalStore.isUserLoggedIn()) {
Log.d("ON CLICK LAW ID", String.valueOf(viewHolder.currentLaw.getId()));
Intent commentsIntent = new Intent(context, DialogCommentsActivity.class);
commentsIntent.putExtra("law_id", viewHolder.currentLaw.getId());
commentsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.d("CURRENT LAW", viewHolder.currentLaw.getId() + " " + viewHolder.currentLaw.getName());
context.startActivity(commentsIntent);
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
break;
case R.id.lawItemDownvote:
if (userLocalStore.isUserLoggedIn()) {
isVotedStorage.setVoted(true, viewHolder.currentLaw.getId());
downvote(viewHolder.currentLaw);
disableIfVoted();
notifyDataSetChanged();
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
break;
case R.id.lawItemUpvote:
if (userLocalStore.isUserLoggedIn()) {
isVotedStorage.setVoted(true, viewHolder.currentLaw.getId());
upvote(viewHolder.currentLaw);
disableIfVoted();
notifyDataSetChanged();
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
break;
}
}
/**
* Holds items per row
*/
private static class ViewHolder {
private TextView tvName;
private TextView tvDescription;
private TextView tvStatus;
private Button btnUpvote;
private Button btnDownvote;
private Button btnMakeComment;
private SurfaceView sfBackground;
private SurfaceView sfLeft;
private Law currentLaw;
}
}
law_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="170dp"
android:gravity="bottom"
android:padding="6pt"
android:background="#color/button_material_light">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="140dp"
android:gravity="bottom"
android:background="#color/background_floating_material_light"
android:theme="#style/AppTheme"
android:id="#+id/rel">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lawItemSurfaceBackground"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<SurfaceView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lawItemSurfaceLeft"
android:layout_alignBaseline="#+id/lawItemSurfaceBackground"
android:layout_alignBottom="#+id/lawItemSurfaceBackground"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lawItemName"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_below="#+id/lawItemSurfaceBackground"
android:layout_marginTop="2pt"
android:layout_marginBottom="3pt"
android:layout_marginLeft="3pt"
android:layout_marginRight="3pt"
android:padding="1pt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lawItemName"
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="1pt"
android:layout_marginLeft="3pt"
android:layout_marginRight="3pt"
android:layout_marginBottom="3pt"
android:id="#+id/lawItemDescription" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1pt"
android:layout_marginBottom="3pt"
android:id="#+id/lawItemStatus"
android:layout_marginRight="30pt"
android:layout_below="#+id/lawItemDescription"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="38dp"
android:layout_below="#id/lawItemStatus"
android:orientation="horizontal">
<Button android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#color/btnSubmitColor"
android:textColor="#color/btnSubmitTextColor"
android:layout_width="match_parent"
android:focusable="false"
android:text="#string/button_upvote"
android:id="#+id/lawItemUpvote" />
<Button android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/btnSubmitColor"
android:textColor="#color/btnSubmitTextColor"
android:text="#string/button_downvote"
android:focusable="false"
android:id="#+id/lawItemDownvote" />
<Button android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/btnSubmitColor"
android:textColor="#color/btnSubmitTextColor"
android:focusable="false"
android:text="#string/button_comment"
android:id="#+id/lawItemMakeComment" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
Example: I click on the btnMakeComment in first row, the new Activity opens and download from db comments of the object with id 15. Then I click on the btnMakeComment in the third row and the new Activity opens and download from db comments of the object with the same id, like last time (again 15).
But in the ListView are not the same rows/objects, they are differentm just on click it seems like they would be the same.
DialogCommentsActivity
/**
* Activity for adding and reading comments
*/
public class DialogCommentsActivity extends AppCompatActivity implements AbsListView.OnItemClickListener, AbsListView.OnScrollListener, View.OnClickListener {
private int lawId;
private int limit;
private int offset;
private int preLast;
private int page;
private ListView listView;
private EditText etAddComment;
private List<Comment> activityCommentList;
private UserLocalStore userLocalStore;
private User user;
private Button btnSubmit;
private CommentsAdapter commentsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments_dialog);
setTitle("");
setFinishOnTouchOutside(true);
listView = (ListView) findViewById(R.id.commentDialogListView);
limit = 5;
offset = 0;
page = 1;
userLocalStore = new UserLocalStore(this);
user = userLocalStore.getLoggedUser();
etAddComment = (EditText) findViewById(R.id.commentDialogEditAdd);
btnSubmit = (Button) findViewById(R.id.commentsDialogSubmit);
btnSubmit.setEnabled(false);
listView.setOnItemClickListener(this);
listView.setOnScrollListener(this);
btnSubmit.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
String userName;
dumpIntent(getIntent());
if (extras != null) {
lawId = extras.getInt("law_id");
}
Log.e("LAW ID HOHOHO", String.valueOf(lawId));
fillAdapter(limit, offset);
etAddComment.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() == 0) {
btnSubmit.setEnabled(false);
} else {
btnSubmit.setEnabled(true);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// 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_detail_law, 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);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
switch(listView.getId()) {
case R.id.commentDialogListView:
Log.d("SCROLL", "scroll");
boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount-1;
if (loadMore) {
page += 1;
// offset = (page * limit) - limit + 1;
// fillAdapter(limit, offset);
// commentsAdapter.notifyDataSetChanged(); TODO
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public void fillAdapter(int limit, int offset) {
ServerRequest serverRequest = new ServerRequest(this);
Log.e("LAWID BEFORE REQUEST", String.valueOf(lawId));
serverRequest.fetchCommentsInBackground(lawId, limit, offset, new GetCommentsCallback() {
#Override
public void done(List<Comment> comments) {
commentsAdapter = new CommentsAdapter(getApplicationContext(), R.layout.comment_item, comments);
listView.setAdapter(commentsAdapter);
activityCommentList = commentsAdapter.getList();
}
});
}
public void loadData(int limit, int offset) {
ServerRequest serverRequest = new ServerRequest(this);
Log.e("LAWID BEFORE REQUEST", String.valueOf(lawId));
serverRequest.fetchCommentsInBackground(lawId, limit, offset, new GetCommentsCallback() {
#Override
public void done(List<Comment> comments) {
// Updating parsed JSON data into ListView
for (Comment comment : comments) {
Log.d("COMMENT OBJECT", comment.getText());
activityCommentList.add(comment);
}
}
});
}
/**
* Handle click events, comments adding
* #param v
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.commentsDialogSubmit:
String text = String.valueOf(etAddComment.getText());
Date dt = new Date();
Log.d("Click", "Click");
if (userLocalStore.isUserLoggedIn()) {
Log.e("LAW ID NEW COMM", String.valueOf(lawId));
Comment comment = new Comment(text, dt, user, lawId);
addComment(comment);
etAddComment.setText("");
//notifyData(limit, offset);
limit = 15;
offset = 0;
fillAdapter(limit, offset);
commentsAdapter.notifyDataSetChanged();
Log.e("NUMBER OF COMMENTS", String.valueOf(activityCommentList.size()));
}
break;
}
}
/**
* Insert comment
* #param comment
*/
public void addComment(Comment comment) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.storeCommentInBackground(comment, new GetCommentsCallback() {
#Override
public void done(List<Comment> list) {
Log.d("Comment", "Comment was added.");
}
});
}
private void dumpIntent(Intent i) {
Bundle bundle = i.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
Log.e("EXTRAS", "Dumping Intent start");
while (it.hasNext()) {
String key = it.next();
Log.e("EXTRAS", "[" + key + "=" + bundle.get(key) + "]");
}
Log.e("EXTRAS", "Dumping Intent end");
}
}
}
SOLUTION:
I added ViewHolder viewHolder = v.getTag(); in every listener (and before it setTag(viewHolder) in getView on every button
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.law_item, parent, false);
this.convertView = convertView;
viewHolder = new ViewHolder();
viewHolder.position = position;
viewHolder.tvName = (TextView) convertView.findViewById(R.id.lawItemName);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.lawItemDescription);
viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.lawItemStatus);
viewHolder.btnDownvote = (Button) convertView.findViewById(R.id.lawItemDownvote);
viewHolder.btnUpvote = (Button) convertView.findViewById(R.id.lawItemUpvote);
viewHolder.btnMakeComment = (Button) convertView.findViewById(R.id.lawItemMakeComment);
viewHolder.btnMakeComment.setTag(viewHolder);
viewHolder.btnDownvote.setTag(viewHolder);
viewHolder.btnUpvote.setTag(viewHolder);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
Log.d("View holder", "get tag");
}
viewHolder.currentLaw = getItem(position);
Log.d("View holder", "new one");
Log.d("LAW ID, ADAPTER", String.valueOf(viewHolder.currentLaw.getId()));
viewHolder.tvName.setText(viewHolder.currentLaw.getName());
viewHolder.tvDescription.setText(viewHolder.currentLaw.getDescription());
viewHolder.tvStatus.setText(viewHolder.currentLaw.getStateValue());
setSurfacesColors();
disableIfVoted();
viewHolder.btnMakeComment.setOnClickListener(onCommentClickListener);
viewHolder.btnDownvote.setOnClickListener(onDowvnvoteClickListener);
viewHolder.btnUpvote.setOnClickListener(onUpvoteClickListener);
// viewHolder.btnMakeComment.setOnClickListener(onCommentClickListener);
return convertView;
}
#Override
public long getItemId(int position) {
return laws.get(position).getId();
}
#Override
public Law getItem(int position) {
return laws.get(position);
}
/**
* On upvote listener
*/
private View.OnClickListener onUpvoteClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag();
if (userLocalStore.isUserLoggedIn()) {
isVotedStorage.setVoted(true, viewHolder.currentLaw.getId());
upvote(viewHolder.currentLaw);
disableIfVoted();
notifyDataSetChanged();
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
}
};
/**
* On downvote listener
*/
private View.OnClickListener onDowvnvoteClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag();
if (userLocalStore.isUserLoggedIn()) {
isVotedStorage.setVoted(true, viewHolder.currentLaw.getId());
downvote(viewHolder.currentLaw);
disableIfVoted();
notifyDataSetChanged();
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
}
};
/**
* On comment listener, open comment dialog
*/
private View.OnClickListener onCommentClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag();
if (userLocalStore.isUserLoggedIn()) {
Log.d("ON CLICK LAW ID", String.valueOf(viewHolder.currentLaw.getId()));
Intent commentsIntent = new Intent(context, DialogCommentsActivity.class);
commentsIntent.putExtra("law_id", viewHolder.currentLaw.getId());
commentsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.d("CURRENT LAW", viewHolder.currentLaw.getId() + " " + viewHolder.currentLaw.getName());
context.startActivity(commentsIntent);
} else {
context.startActivity(new Intent(context, DialogSignInActivity.class));
}
}
};
Your are getting last id/ last row position every time because last view reders at last
To get row position on button click you can set postion as tags to your buttons and check that tags in onclickListner
For example in your getview() method put position as tag in viewHolder.btnMakeComment button
viewHolder.btnMakeComment.setTag(position); and in OnClickListner Check tag
int position = (int)v.getTag();
Change your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.law_item, parent, false);
this.convertView = convertView;
viewHolder = new ViewHolder();
viewHolder.tvName = (TextView) convertView.findViewById(R.id.lawItemName);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.lawItemDescription);
viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.lawItemStatus);
viewHolder.btnDownvote = (Button) convertView.findViewById(R.id.lawItemDownvote);
viewHolder.btnUpvote = (Button) convertView.findViewById(R.id.lawItemUpvote);
viewHolder.btnMakeComment = (Button) convertView.findViewById(R.id.lawItemMakeComment);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
Log.d("View holder", "get tag");
}
viewHolder.currentLaw = getItem(position);
Log.d("View holder", "new one");
Log.d("LAW ID, ADAPTER", String.valueOf(viewHolder.currentLaw.getId()));
viewHolder.tvName.setText(viewHolder.currentLaw.getName());
viewHolder.tvDescription.setText(viewHolder.currentLaw.getDescription());
viewHolder.tvStatus.setText(viewHolder.currentLaw.getStateValue());
setSurfacesColors();
viewHolder.btnMakeComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//position -> get id
//action
}
})
viewHolder.btnDownvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//position -> get id
//action
}
});
viewHolder.btnUpvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//position -> get id
//action
}
});
disableIfVoted();
return convertView;
}
try this bt i am not sure:
ArrayList<String> Ex=new ArrayList<String>();
for (int i = 0 ; i<youriDvalue.length; i++)
{
Ex.add(currentVerse_speak.get(i));
//(or)
String []ex1;
ex1=currentVerse_speak.get(i)+"~";
exi[i]=currentVerse_speak.get(i).toString();
}
txtview.settext(Ex.toString());
txtview.settext(ex1.tosting());
I have added two spinners on custom adapter list view. All is good but when I add new item to list view then value of previous item's spinner is transformed to new item. And on scrolling list view values of spinners also rotates. Any Help please.
public class CustomAdapter extends BaseAdapter {
private ArrayList<MyMessageDetails> _data;
Context _c;
ProductsItemViewHolder holder;
CustomAdapter (ArrayList<MyMessageDetails> data, Context c){
_data = data;
_c = c;
}
public int getCount() {
// TODO Auto-generated method stub
return _data.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return _data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
final MyMessageDetails msg = _data.get(position);
if (v == null)
{
LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listview_item_row, null);
holder = new ProductsItemViewHolder();
holder.image = (ImageView) v.findViewById(R.id.icon);
holder.fromView = (TextView) v.findViewById(R.id.textView1);
holder.spinnersizes = (Spinner) v.findViewById(R.id.spinner1);
holder.spinnercopies = (Spinner) v.findViewById(R.id.spinner2);
String Photo_copies[];
Photo_copies=new String[100];
int x = 1;
while( x < 101 ) {
if(x == 1){
Photo_copies[x-1]= String.valueOf(x) + " Copy";
}else{
Photo_copies[x-1]= String.valueOf(x) + " Copies";
}
x++;
}
String array_spinner[];
array_spinner=new String[5];
array_spinner[0]="4x6|Plastic|RS 20";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
ArrayAdapter adapter = new ArrayAdapter(_c,android.R.layout.simple_spinner_item, array_spinner);
ArrayAdapter adapter2 = new ArrayAdapter(_c,android.R.layout.simple_spinner_item, Photo_copies);
holder.spinnersizes.setAdapter(adapter);
holder.spinnercopies.setAdapter(adapter2);
holder.spinnercopies.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
String sizes = holder.spinnersizes.getSelectedItem().toString();
holder.spinnersizes.setTag(position);
String copies = holder.spinnercopies.getSelectedItem().toString();
String mycopies = copies;
String myprice = sizes;
myprice = myprice.substring(myprice.lastIndexOf(" ") + 1);
mycopies = mycopies.substring(0, mycopies.lastIndexOf(" "));
int finalprice = Integer.parseInt(myprice) * Integer.parseInt(mycopies);
holder.fromView.setText(holder.image.getTag().toString() + " Copies:" + mycopies + " Price:" + finalprice);
msg.setCopies(mycopies);
msg.setSize(String.valueOf(finalprice));
// lab_gallery.Calculate_Bill();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.spinnersizes.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
// your code here
String sizes = holder.spinnersizes.getSelectedItem().toString();
holder.spinnersizes.setTag(position);
String copies = holder.spinnercopies.getSelectedItem().toString();
String mycopies = copies;
String myprice = sizes;
myprice = myprice.substring(myprice.lastIndexOf(" ") + 1);
mycopies = mycopies.substring(0, mycopies.lastIndexOf(" "));
int finalprice = Integer.parseInt(myprice) * Integer.parseInt(mycopies);
holder.fromView.setText(holder.image.getTag().toString() + " Copies:" + mycopies + " Price:" + finalprice);
msg.setCopies(mycopies);
msg.setSize(String.valueOf(finalprice));
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.image.setImageBitmap(msg.getIcon());
holder.fromView.setTag(msg.getUrl());
holder.fromView.setText(msg.getName());
holder.image.setTag(msg.getName());
msg.setCopies("1");
msg.setSize("20");
v.setTag(holder);
} else {
holder = (ProductsItemViewHolder) v.getTag();
}
if (holder.spinnersizes.getTag() != null){
holder.spinnersizes.setSelection(Integer.parseInt(holder.spinnersizes.getTag().toString()));
}
//image.setScaleType(ScaleType.FIT_XY);
return v;
}
static class ProductsItemViewHolder {
ImageView image;
TextView fromView;
Spinner spinnersizes;
Spinner spinnercopies;
}
}
This is because of view recycling. View are recycled with the last state. If your spinner had something selected, and if that view is reused it'll also pick the state of the spinner. You need to add logic to preserve state of your Spinners. You can maintain a dictionary with row position and selectedIndex.
//Class level field
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
inside your getView() method check if we have a state saved for the spinner at this row psition
if (myMap.containsKey(position)) {
spinner.setSelection(myMap.get(position));
}
Saving state when an item is selected in spinner
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int selectedIndex, long id) {
//...
myMap.put(position, selectedIndex);
//...
}
I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.