I am tryin to make a quiz app with translations. So there are two ArrayLists with Question Loaded in differnt languages.
I can show them in the List View as well. My problem is when I click on One Radiobutton I want the other Radiobutton to get selected as well.
I am using a ListView with a custom layout with 2 Radiobuttons .
This is my ArrayAdater for ListView
private class RBAdapterClass extends ArrayAdapter<cOptions> {
private ArrayList<cOptions> fOptions;
private ArrayList<cOptions> lOptions;
private ArrayList<Boolean> mChecked;
private int mfSelectedPosition = -1;
private RadioButton mfSelectedRB;
private int mlSelectedPosition = -1;
private RadioButton mlSelectedRB;
public RBAdapterClass(Context context, int textViewResourceId, ArrayList<cOptions> lOpt, ArrayList<cOptions> fOpt)
{
super(context,textViewResourceId,fOpt);
this.fOptions = new ArrayList<cOptions>();
this.fOptions.addAll(fOpt);
this.lOptions = new ArrayList<cOptions>();
this.lOptions.addAll(lOpt);
mChecked = new ArrayList<Boolean>();
}
class ViewHolder {
TextView ForeignCode;
RadioButton ForeignName;
TextView LocalCode;
RadioButton LocalName;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holderf ;
Log.v("Convert View",String.valueOf(position));
if(convertView==null){
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_activity_rb,null);
holderf=new ViewHolder();
holderf.LocalCode = (TextView) convertView.findViewById(R.id.codeLocal);
holderf.LocalName = (RadioButton)convertView.findViewById(R.id.radioBLocal);
holderf.ForeignCode = (TextView) convertView.findViewById(R.id.codeForeign);
holderf.ForeignName = (RadioButton)convertView.findViewById(R.id.radioBForeign);
convertView.setTag(holderf);
holderf.ForeignName.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
RadioButton rb = (RadioButton) v ;
if(position != mfSelectedPosition && mfSelectedRB!=null )
{
mfSelectedRB.setChecked(false);
if(mlSelectedRB!=null)
{
mlSelectedRB.setChecked(false);
}
}
mfSelectedPosition = position;
mfSelectedRB = (RadioButton)v;
cOptions optSelected = (cOptions) rb.getTag();
Toast.makeText(getApplicationContext(),"Clicked on RadioButton: " + rb.getText() +" is " + rb.isChecked(),
Toast.LENGTH_LONG).show();
optSelected.setSeleted(rb.isChecked());
holderf.ForeignName.setChecked(rb.isChecked());
holderf.LocalName.setChecked(rb.isChecked());
}
});
holderf.LocalName.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
if(position != mlSelectedPosition && mlSelectedRB!=null)
{
mlSelectedRB.setChecked(false);
if(mfSelectedRB!=null)
{
mfSelectedRB.setChecked(false);
}
}
mlSelectedPosition = position;
mlSelectedRB = (RadioButton)v;
RadioButton rb = (RadioButton) v ;
cOptions optSelected = (cOptions) rb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on RadioButton: " + rb.getText() +" is " + rb.isChecked(),Toast.LENGTH_LONG).show();
optSelected.setSeleted(rb.isChecked());
holderf.ForeignName.setChecked(rb.isChecked());
holderf.LocalName.setChecked(rb.isChecked());
}
});
}
else
{
holderf = (ViewHolder) convertView.getTag();
}
cOptions optfSelected = fOptions.get(position);
cOptions optlSelected = lOptions.get(position);
if(mlSelectedPosition!=position)
{
holderf.ForeignCode.setText(" (" + optfSelected.getsOptionsText() + ")");
holderf.ForeignName.setText(optfSelected.getsOptionsText());
holderf.ForeignName.setChecked(optfSelected.getSeleted());
holderf.ForeignName.setTag(optfSelected);
holderf.LocalCode.setText("("+optlSelected.getsOptionsText()+")");
holderf.LocalName.setText(optlSelected.getsOptionsText());
holderf.LocalName.setChecked(optlSelected.getSeleted());
holderf.LocalName.setTag(optlSelected);
}
else
{
holderf.ForeignCode.setText(" (" + optfSelected.getsOptionsText() + ")");
holderf.ForeignName.setText(optfSelected.getsOptionsText());
holderf.ForeignName.setChecked(optfSelected.getSeleted());
holderf.ForeignName.setTag(optfSelected);
holderf.LocalCode.setText("("+optlSelected.getsOptionsText()+")");
holderf.LocalName.setText(optlSelected.getsOptionsText());
holderf.LocalName.setChecked(optlSelected.getSeleted());
holderf.LocalName.setTag(optlSelected);
}
return convertView;
}
}
}
There is no check box in your code. Think it will be Radio button instead. I can't understand why do you want both radio buttons to be checked. Anyway, if you are setting those separately, (Not inside a RadioGroup), then you can make both checked at a time.
One suggession: write your onClick listeners outside the if-else block
Related
I have some error in android studio.
When i try to add symbol ('*') to special item, it also add the symbol to the item that placed in +14 from the first.
I will glad if someone have solution for this problem.
For more information you can check this link, where i describe the problem.
https://youtu.be/CJFkt-Cck1A
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
private Context context;
private List<WorkDayItem> workDayItemList;
//Complete
public RecyclerViewAdapter(Context context, List<WorkDayItem> workDayItemList) {
this.context = context;
this.workDayItemList = workDayItemList;
}
//Complete
//Here we create view- itemWorkday and inflate it by layout- item_one_work_day
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemWorkDay = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_one_work_day, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(itemWorkDay);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called." + (position + 1) + "\n" + workDayItemList.get(position).toString());
final WorkDayItem workDayItem = workDayItemList.get(position);
String dateStart = (String) DateFormat.format("dd.MM", workDayItem.getDateStart());
String timeStart = (String) DateFormat.format("HH:mm", workDayItem.getDateStart());
String timeEnd = (String) DateFormat.format("HH:mm", workDayItem.getDateEnd());
//Convert data from firebase String format to int hours and minutes format.
Double convertingDataFromFirebase;
try {
convertingDataFromFirebase = Double.parseDouble(new DecimalFormat("##.##").format(workDayItem.getCount_hours()));
} catch (NumberFormatException e) {
convertingDataFromFirebase = 0.0;
}
int hours = convertingDataFromFirebase.intValue();
convertingDataFromFirebase = (convertingDataFromFirebase - convertingDataFromFirebase.intValue()) * 60;
int minutes = convertingDataFromFirebase.intValue();
//Check if current item have description
if (workDayItemList.get(position).getDesc().length() > 2) {
Log.i(TAG, "TESTER: desc dote added");
holder.doteOfDesc.setVisibility(View.VISIBLE);
}
holder.dayPosition.setText((position + 1) + "");
holder.dateStart.setText(dateStart);
holder.timeStart.setText(timeStart);
holder.timeEnd.setText(timeEnd);
holder.countOfHours.setText(hours + ":" + minutes);
//On click on current hold open alert dialog with some functions
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeAlertDialogForItem(workDayItem, holder);
}
});
}
//initialize data about current work day and have button for changing information
private void initializeAlertDialogForItem(final WorkDayItem workDayItem, final MyViewHolder holder) {
//Initialize alert dialog
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
View itemWork = LayoutInflater.from(context)
.inflate(R.layout.ad_item_desc, null, false);
alertDialog.setView(itemWork);
alertDialog.show();
//initialize alert dialog buttons and views
final ImageButton change = alertDialog.findViewById(R.id.itemAD_Edit);
final ImageButton delete = alertDialog.findViewById(R.id.itemAD_Delete);
TextView description = alertDialog.findViewById(R.id.itemADDescription);
TextView date = alertDialog.findViewById(R.id.itemADDate);
TextView from = alertDialog.findViewById(R.id.itemADFrom);
TextView to = alertDialog.findViewById(R.id.itemADTO);
String timeStart = (String) (DateFormat.format("HH:mm", workDayItem.getDateStart()));
String timeEnd = (String) (DateFormat.format("HH:mm", workDayItem.getDateEnd()));
String dateStart = (String) (DateFormat.format("dd.MM.yyyy", workDayItem.getDateStart()));
date.setText(dateStart);
from.setText(timeStart);
to.setText(timeEnd);
description.setText(workDayItem.getDesc());
//Change button
change.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
AlertDialogReport userReport = new AlertDialogReport(context, "replace-remove", workDayItem);
userReport.initializeAlertDialog();
alertDialog.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Delete data from firebase
Login.fc.databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String itemTime = "" + workDayItem.getDateStart().getTime();
String firebaseTime = "" + snapshot.child("dateStart").child("time").getValue();
if (itemTime.equals(firebaseTime)) {
Login.fc.databaseReference.child(snapshot.getKey()).removeValue();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//Delete data from SqLiteDatabase
MySQLDataBase dataBase = new MySQLDataBase(context);
dataBase.deleteItem(workDayItem);
//Finish with alert dialog and notify user
alertDialog.dismiss();
Toast.makeText(context, R.string.item_deleted, Toast.LENGTH_SHORT).show();
holder.parentLayout.removeAllViews();
}
});
}
//Complete
#Override
public int getItemCount() {
return workDayItemList.size();
}
//Complete
//Here we catch our view and getting reference between view and our objects
public class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout parentLayout;
private TextView doteOfDesc, dayPosition, dateStart, timeStart, timeEnd, countOfHours;
public MyViewHolder(View view) {
super(view);
doteOfDesc = view.findViewById(R.id.itemDote);
dayPosition = view.findViewById(R.id.itemDayPosition);
dateStart = view.findViewById(R.id.itemDateStart);
timeStart = view.findViewById(R.id.itemStartHour);
timeEnd = view.findViewById(R.id.itemEndHour);
countOfHours = view.findViewById(R.id.itemCountOfHours);
parentLayout = view.findViewById(R.id.itemWorkDay);
}
}
}
Try adding this:
//Check if current item have description
if (workDayItemList.get(position).getDesc().length() > 2) {
Log.i(TAG, "TESTER: desc dote added");
holder.doteOfDesc.setVisibility(View.VISIBLE);
}
else if( workDayItemList.get(position).getDesc().length() < 2
&& holder.doteOfDesc.getVisibility()== View.VISIBLE ){
holder.doteOfDesc.setVisibility(View.GONE);
}
The reason why this is happening is that RecyclerView creates as many ViewHolders as its needed to cover a whole screen plus few extra ( 12 in your case) then reuses them via rebinding values to views. And you set doteOfDescto View.VISIBLE in 2. ViewHolder, but never set it back to View.GONE, thats why every time that ViewHolder is reused it will have doteOfDesc visible.
The Prettier version:
Boolean hasDescription = workDayItemList.get(position).getDesc().length() > 2;
holder.doteOfDesc.setVisibility( hasDescription ? View.VISIBLE : View.GONE);
I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.
In list View I created Programmatically Image view and added in Linear Layout inside of ListView item.Below code I use for add Images in Adapter. Then how to get That image position.
Below I added my getView() method. I'm getting multiple Images in "String[] childDocument". using for loop I Sepreted Images from String[] and add in Linear Layout.
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ApproveReimbBin item = getItem(position);
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
String date = item.getStr_startDate();
String[] splitDate = date.split("To");
String profileName = item.getStr_name();
String profileEmpId = item.getStr_empId();
String profileType = item.getStr_type();
String profileAmount = item.getStr_amount();
final String[] childDocument = item.getStr_documents();
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.adapter_approvereimburs, parent, false);
// binding view parts to view holder
viewHolder.imag_listProfileImage = cell.findViewById(R.id.list_image);
viewHolder.txt_listName = cell.findViewById(R.id.list_profileName);
viewHolder.txt_listEmpId = cell.findViewById(R.id.list_profileEmpId);
viewHolder.txt_listType = cell.findViewById(R.id.list_profileType);
viewHolder.image_childProfileImage = cell.findViewById(R.id.child_profile_img);
viewHolder.txt_name = cell.findViewById(R.id.txt_profile_name);
viewHolder.txt_empId = cell.findViewById(R.id.txt_profile_id);
viewHolder.txt_type = cell.findViewById(R.id.txt_profile_type);
viewHolder.txt_frmDate = cell.findViewById(R.id.txt_from_date);
viewHolder.txt_toDate = cell.findViewById(R.id.txt_to_date);
viewHolder.txt_amount = cell.findViewById(R.id.txt_amount);
viewHolder.btn_reject = cell.findViewById(R.id.btn_reject);
viewHolder.btn_approve = cell.findViewById(R.id.btn_approve);
viewHolder.linearLayout = cell.findViewById(R.id.linearLayout_Image);
cell.setTag(viewHolder);
} else {
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
Log.e("suraj", "unfold call");
} else {
cell.fold(true);
Log.e("suraj", "fold call");
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == item)
return cell;
String ImageUrl = ServerUrls.Web.IMAGE_URL + profileEmpId.trim() + ".jpg";
ImageView image;
if (viewHolder.linearLayout.getChildCount() > 0) {
viewHolder.linearLayout.removeAllViews();
}
for (int i = 0; i < childDocument.length; i++) {
String doc = childDocument[i].replace("~", "");
doc = doc.replace("\\", "/");
doc = doc.replace(",", "");
image = new ImageView(mContext);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100, 100));
image.setMaxHeight(100);
image.setMaxWidth(100);
Log.e("surajjj", "for loop use " + imageDocument.trim() + doc);
Picasso.with(mContext)
.load(imageDocument.trim() + doc)
.error(R.drawable.doc_img)
.into(image);
viewHolder.linearLayout.addView(image);
int lent = childDocument.length;
Log.e("surajj", "docu " + imageDocument.trim() + doc + " position " + i + " lenth " + lent);
}
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int sr = viewHolder.linearLayout.indexOfChild(view);
Toast.makeText(mContext, "Postition is "+ sr, Toast.LENGTH_SHORT).show();
}
});
viewHolder.linearLayout.getChildAt(position).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, childDocument.toString(), Toast.LENGTH_SHORT).show();
}
});
Picasso.with(mContext)
.load(ImageUrl.trim())
.error(R.drawable.ic_user)
.into(viewHolder.imag_listProfileImage);
Picasso.with(mContext)
.load(ImageUrl.trim())
.error(R.drawable.ic_user)
.into(viewHolder.image_childProfileImage);
if (profileName != null || !profileName.equals(" ")) {
viewHolder.txt_listName.setText(profileName);
viewHolder.txt_name.setText(profileName);
}
if (profileEmpId != null || !profileEmpId.equals(" ")) {
viewHolder.txt_listEmpId.setText(profileEmpId);
viewHolder.txt_empId.setText(profileEmpId);
}
if (profileType != null || !profileType.equals(" ")) {
viewHolder.txt_listType.setText(profileType);
viewHolder.txt_type.setText(profileType);
}
if (profileAmount != null || !profileAmount.equals(" ")) {
viewHolder.txt_amount.setText(profileAmount);
}
if (splitDate != null || !splitDate.equals(" ")) {
if (splitDate.length == 2) {
Log.d("suraj1", "fromDate " + splitDate[0] + " toDate " + splitDate[1]);
viewHolder.txt_frmDate.setText(splitDate[0]);
viewHolder.txt_toDate.setText(splitDate[1]);
} else {
Log.d("suraj1", "onlyfromDate " + splitDate[0]);
viewHolder.txt_frmDate.setText(splitDate[0]);
}
}
viewHolder.btn_approve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestId = item.getStr_requestId();
reimbursmentId = item.getStr_reimbursementid();
action = "Approved";
Methods.showProgressDialog(mContext);
unfoldedIndexes.clear();
new asyncSendRequest().execute();
}
});
viewHolder.btn_reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestId = item.getStr_requestId();
reimbursmentId = item.getStr_reimbursementid();
action = "Rejected";
Methods.showProgressDialog(mContext);
unfoldedIndexes.clear();
new asyncSendRequest().execute();
}
});
return cell;
}
In this Image I'm dynamically added images. I want this perticular image position.
This question already has answers here:
custom listview adapter getView method being called multiple times, and in no coherent order
(12 answers)
Closed 6 years ago.
Java code
public class ContentListAdapter extends ArrayAdapter<Content> implements Filterable {
//private static final String TAG = ContentListAdapter.class.getCanonicalName();
private static final LogTracer LOG_TRACER = LogTracer.instance(ContentListAdapter.class);
private Context mContext;
private LayoutInflater mInflater;
private List<Content> mContents;
private List<Content> mContentsFiltered;
private int lastPosition = -1;
private boolean multiselectMode = false;
private Customer mCustomer = null;
private AdapterView.OnItemClickListener mOnItemClickListener;
private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
PatientRatingDAO patientRatingDAO;
int completeVisiblePosition=0;
public int totalScrollCount= 0;
private boolean isFromHomeSearch;
private ListView mListView;
public View helpView;
public ContentListAdapter(Context context, List<Content> contents, ListView listView) {
super(context, R.layout.list_content, contents);
mContext = context;
mContents = contents;
mListView = listView;
mContentsFiltered = contents;
mInflater = LayoutInflater.from(mContext);
mCustomer = new CustomerDAO(context).getCurrentCustomer();
patientRatingDAO = new PatientRatingDAO(getContext());
}
private class ViewHolder {
View listContent;
ImageButton contentThumbnail, contentThumbnailNew,typeofarticle;
LinearLayout contentRightSec;
LinearLayout contentRightSecBottom;
TextView fileSize;
LinearLayout tagsView;
TextView contentPostTime;
TextView contentDescription;
TextView contentSource;
LinearLayout rateCountSec;
LinearLayout rateBarLayout;
TextView rateCount;
TextView likeCount;
TextView likeText;
ImageView likeImage,likeCountImage,rateCountImage,readtick;
RatingBar ratingBar;
RatingBar disabledRatingBar;
RelativeLayout patienteducation;
//int isLiked;
//int currentUserRateCount;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
// assign the view we are converting to a local variable
View v = convertView;
LOG_TRACER.d("parm getView " + position + " " + convertView);
// Calculating Scroll Count
if(getCompleteVisiblePosition() == 0){
if(v != null && mListView != null){
this.setCompleteVisiblePosition(calculateCompletelyVisibleListItems(v));
LOG_TRACER.d("parm completeVisiblePosition" + completeVisiblePosition);
}
}
if(getCompleteVisiblePosition() > 0){
if(position % getCompleteVisiblePosition() == 0){
totalScrollCount++;
LOG_TRACER.d("parm totalScrollCount" + totalScrollCount);
}
}
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//v = inflater.inflate(mLayout, null);
v = LayoutInflater.from(mContext).inflate(R.layout.list_content, parent, false);
ViewHolder holder = new ViewHolder();
holder.rateCount = (TextView) v.findViewById(R.id.rateCount);
holder.likeCount = (TextView) v.findViewById(R.id.likeCount);
holder.likeCountImage = (ImageView) v.findViewById(R.id.likeCountImage);
holder.rateCountImage = (ImageView) v.findViewById(R.id.rateCountImage);
holder.likeText = (TextView) v.findViewById(R.id.like_text);
holder.likeImage = (ImageView) v.findViewById(R.id.like_image);
holder.ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
holder.disabledRatingBar = (RatingBar) v.findViewById(R.id.disabled_rating_bar);
holder.typeofarticle = (ImageButton) v.findViewById(R.id.typeofarticle);
holder.patienteducation = (RelativeLayout) v.findViewById(R.id.patient_education);
v.setTag(holder);
}
final Content content = getItem(position);
final ViewHolder viewHolder = (ViewHolder) v.getTag();
if(viewHolder.listContent != null) {
if(content.getIs_Read() == Constants.INT_FLAG_YES) {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_grey);
viewHolder.readtick.setVisibility(View.VISIBLE);
} else {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_white);
viewHolder.readtick.setVisibility(View.GONE);
}
if(viewHolder.contentThumbnailNew != null){
Ion.with(viewHolder.contentThumbnailNew).fitXY().placeholder(R.drawable.imagethumbnail).fitXY().error(R.drawable.imagethumbnail).fitXY().load(
(!TextUtils.isEmpty(content.getDA_Thumbnail_Url()))?content.getDA_Thumbnail_Url().replaceAll(" ","%20") : content.getDA_Thumbnail_Url());
}
if(viewHolder.contentThumbnail != null) {
viewHolder.contentThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
} else {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
}
}
});
viewHolder.contentThumbnailNew.setOnTouchListener(new TouchExtendedClickListener(mContext, new TouchExtendedClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view) {
if (mOnItemClickListener != null) mOnItemClickListener.onItemClick(null, convertView, position, position);
}
}));
viewHolder.contentThumbnailNew.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
}
return true;
}
});
}
}
}
//To Set Ratings
if (viewHolder.rateCount != null) {
//Calculate rate count by (totalratigs/numberofusersrated)
if(content.getTotalRatings() == 0 || content.getTotalRatedCount()==0){
viewHolder.rateCount.setText("0");
}else if(content.getTotalRatedCount() != 0){
viewHolder.rateCount.setText(String.valueOf(Math.round(content.getTotalRatings()/content.getTotalRatedCount())));
}
}
//To Set Likes
if (viewHolder.likeCount != null) {
viewHolder.likeCount.setText(String.valueOf(content.getLikes()));
}
//if viewHolder.isLiked == 0 then user not yet liked else if viewHolder.isLiked == 1 the user liked
//viewHolder.isLiked = content.getIsLiked();
//viewHolder.currentUserRateCount = content.getCurrentUserRateCount();
//Add Like Listeners
if (viewHolder.likeText != null && viewHolder.likeImage != null) {
if(content.getIsLiked() == 0){
//Set liked image and text
viewHolder.likeText.setText("Like");
viewHolder.likeImage.setImageResource(R.drawable.ic_like_grey_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_grey_24dp);
}else{
//Set liked image and text
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
}
viewHolder.likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (content.getIsLiked() == 0) {
content.setIsLiked(1);
//To insert/update user likes to local database
PatientRating patientRating = patientRatingDAO.getByDACodeAndType(content.getDA_Code(),content.getContent_Type());
if(patientRating != null){
patientRating.setIsLiked(content.getIsLiked());
patientRatingDAO.update(patientRating);
}else{
patientRating = new PatientRating();
patientRating.setIsLiked(1);
patientRating.setContent_Type(content.getContent_Type());
patientRating.setDA_Code(content.getDA_Code());
patientRatingDAO.insert(patientRating);
}
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
//Increase like counts
int likes = 1 + Integer.parseInt(viewHolder.likeCount.getText().toString());
viewHolder.likeCount.setText(String.valueOf(likes));
viewHolder.rateBarLayout.setVisibility(View.VISIBLE);
Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.like_animation);
viewHolder.likeImage.startAnimation(animation);
//Toast.makeText(mContext, "Liked", Toast.LENGTH_SHORT).show();
return v;
}
#Override
public int getCount() {
return mContentsFiltered.size();
}
#Override
public Content getItem(int position) {
return mContentsFiltered.get(position);
}
public Filter getFilter(FilterOption filterOption) {
return getFilter();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase().trim();
FilterResults results = new FilterResults();
final List<Content> list = mContents;
int count = list.size() - 1;
List<Content> nlist = new ArrayList<Content>(list.size());
Content filterableContent;
for (int i = 0; i <= count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
} else if (!TextUtils.isEmpty(filterableContent.getTags())
&& filterableContent.getTags().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}else if (!TextUtils.isEmpty(filterableContent.getCompany_Name())
&& filterableContent.getCompany_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}
}
/*List<Integer> companyIds = StaticVariableUtils.getFilterOption().getFilterCompanyIds();
for (int i = 0; i < count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
// if company ids are selected, check if
// the filtered content has slected company id
if(companyIds != null && companyIds.size() >= 1) {
if(companyIds.indexOf(filterableContent.getCompany_Id()) >= 0) {
nlist.add(filterableContent);
}
} else {
nlist.add(filterableContent);
}
}
}
List<Content> tmpList = new ArrayList<>(nlist.size());
if(nlist != null) {
// sort by datetime
Collections.sort(nlist, new Comparator<Content>() {
#Override
public int compare(Content lhs, Content rhs) {
if(StaticVariableUtils.getFilterOption().getSortingOrder() == R.string.sortingOrderLatest) {
return (lhs.getUploaded_Date().getTime()>rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
} else {
return (lhs.getUploaded_Date().getTime()<rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
}
}
});
}
FilterOption filterOption = StaticVariableUtils.getFilterOption();
if(filterOption.getShowByDate() == R.string.showByDateToday) {
nlist = filterByToday(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastWeek) {
nlist = filterByLastWeek(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateTwoWeeks) {
nlist = filterByTwoWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateThreeWeeks) {
nlist = filterByThreeWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastMonth) {
nlist = filterByLastMonth(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateOlder) {
nlist = filterByOlder(nlist);
}
if(filterOption.getShowByStatus() != R.string.showByStatusAll) {
nlist = getReadOrUnread(nlist, filterOption.getShowByStatus());
}*/
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mContentsFiltered = (ArrayList<Content>) results.values;
notifyDataSetChanged();
}
};
}
my xml file
<ListView
android:id="#+id/lvContent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e2e2e2"
android:clipToPadding="false"
android:divider="#null"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:smoothScrollbar="true"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:scrollbarStyle="insideOverlay">
</ListView>
getView method in Adapter of list view call multiple time at postion 0
So it is Taking a more time to Load this Activity.This codes are i am using....i don't know why getview() calls more than one time.and my working code is above.. how to Resolve this issue.
I Resolve this issuee...... Because i added list from three different methods and also set notifydatasetchange. so my get view called more than one time....
In a listview, on each row, I have 10 buttons. When any of those buttons pressed, color of the buttons should changed (its like filling the bar based on where you pressed) .
Here is what I've done so far:
I have added references of each button to an ArrayList called buttons.
Also, I have an ArrayList which has colors strings.
This is click listener that is assigned to each button.
This is complete code form my adapter class of the listview.
public class TeacherRatingAdapter extends ArrayAdapter<Votes> {
private ArrayList<String> colors = new ArrayList();
private ArrayList<Button> buttons = new ArrayList<>();
private LayoutInflater inflater;
private ArrayList<Votes> mItems = new ArrayList<>();
private ArrayList<Votes> mItemsTemp = new ArrayList<>();
private int teacher;
private boolean myTeacher;
private ArrayList<Pair<Integer, Integer>> questionHint = new ArrayList<>();
private static int givenMark;
private HashMap<String, Integer> givenMarks = new HashMap<>();
ViewHolder viewHolder;
public TeacherRatingAdapter(Context context, TeacherRating teacherRating) {
super(context, -1, teacherRating.getVotes());
mItems = teacherRating.getVotes();
if(mItems.size()==0){
for(int i = 0; i<10; i++){
mItems.add(new Votes());
}
}
for(int i = 0; i<teacherRating.getVotes().size(); i++){
givenMarks.put(String.valueOf(i+1), teacherRating.getVotes().get(i).getAll().get(i));
}
teacher = teacherRating.getTeacher();
myTeacher = teacherRating.isMy_teacher();
questionHint.add(new Pair<>(R.string.question1, R.string.questionHint1));
questionHint.add(new Pair<>(R.string.question2, R.string.questionHint2));
questionHint.add(new Pair<>(R.string.question3, R.string.questionHint3));
questionHint.add(new Pair<>(R.string.question4, R.string.questionHint4));
questionHint.add(new Pair<>(R.string.question5, R.string.questionHint5));
questionHint.add(new Pair<>(R.string.question6, R.string.questionHint6));
questionHint.add(new Pair<>(R.string.question7, R.string.questionHint7));
questionHint.add(new Pair<>(R.string.question8, R.string.questionHint8));
questionHint.add(new Pair<>(R.string.question9, R.string.questionHint9));
questionHint.add(new Pair<>(R.string.question10, R.string.questionHint10));
colors.add("#E77272");
colors.add("#E77D72");
colors.add("#E78D72");
colors.add("#E7A472");
colors.add("#E8B472");
colors.add("#E8C272");
colors.add("#E8C272");
colors.add("#E6E773");
colors.add("#c3e874");
colors.add("#89e874");
}
#Override
public int getCount() {
return mItems.size() > 0 ? mItems.size() : 1;
}
#Override
public boolean isEnabled(int position) {
return mItems.size() != 0;
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button = (Button) v;
String text = button.getText().toString();
if(text.equals("1")){
givenMark = 1;
}else if(text.equals("2")){
givenMark = 2;
}else if(text.equals("3")){
givenMark = 3;
}else if(text.equals("4")){
givenMark = 4;
}else if(text.equals("5")){
givenMark = 5;
}else if(text.equals("6")){
givenMark = 6;
}else if(text.equals("7")){
givenMark = 7;
}else if(text.equals("8")){
givenMark = 8;
}else if(text.equals("9")){
givenMark = 9;
}else if(text.equals("10")){
givenMark = 10;
}
colorButton(givenMark, viewHolder);
// button.setBackgroundColor(Color.parseColor(colors.get(givenMark)));
mItems.get(Integer.valueOf(button.getTag().toString())).addOne(Integer.valueOf(text));
// mItems.get(Integer.valueOf(button.getTag().toString())).setScore(Integer.valueOf(text), givenMark);
// givenMarks.put(button.getTag().toString(), givenMark);
notifyDataSetChanged();
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = LayoutInflater.from(getContext());
if (mItems.size() == 0) {
if (!Common.isNetworkConnected(getContext())) {
convertView = inflater.inflate(R.layout.list_item_no_internet, null, false);
} else {
convertView = inflater.inflate(R.layout.list_item_no_content, null, false);
}
return convertView;
} else {
if (convertView == null) {
buttons.clear();
convertView = inflater.inflate(R.layout.list_item_teacher_rating, parent, false);
viewHolder = new ViewHolder();
viewHolder.mQuestionTextView = (TextView) convertView.findViewById(R.id.question);
viewHolder.mHintTextView = (TextView) convertView.findViewById(R.id.question_hint);
viewHolder.button1 = (Button) convertView.findViewById(R.id.question_button_1);
viewHolder.button2 = (Button) convertView.findViewById(R.id.question_button_2);
viewHolder.button3 = (Button) convertView.findViewById(R.id.question_button_3);
viewHolder.button4 = (Button) convertView.findViewById(R.id.question_button_4);
viewHolder.button5 = (Button) convertView.findViewById(R.id.question_button_5);
viewHolder.button6 = (Button) convertView.findViewById(R.id.question_button_6);
viewHolder.button7 = (Button) convertView.findViewById(R.id.question_button_7);
viewHolder.button8 = (Button) convertView.findViewById(R.id.question_button_8);
viewHolder.button9 = (Button) convertView.findViewById(R.id.question_button_9);
viewHolder.button10 = (Button) convertView.findViewById(R.id.question_button_10);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button2.setOnClickListener(clickListener);
viewHolder.button3.setOnClickListener(clickListener);
viewHolder.button4.setOnClickListener(clickListener);
viewHolder.button5.setOnClickListener(clickListener);
viewHolder.button6.setOnClickListener(clickListener);
viewHolder.button7.setOnClickListener(clickListener);
viewHolder.button8.setOnClickListener(clickListener);
viewHolder.button9.setOnClickListener(clickListener);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button1.setTag(position);
viewHolder.button2.setTag(position);
viewHolder.button3.setTag(position);
viewHolder.button4.setTag(position);
viewHolder.button5.setTag(position);
viewHolder.button6.setTag(position);
viewHolder.button7.setTag(position);
viewHolder.button8.setTag(position);
viewHolder.button9.setTag(position);
viewHolder.button1.setTag(position);
buttons.add(viewHolder.button1);
buttons.add(viewHolder.button2);
buttons.add(viewHolder.button3);
buttons.add(viewHolder.button4);
buttons.add(viewHolder.button5);
buttons.add(viewHolder.button6);
buttons.add(viewHolder.button7);
buttons.add(viewHolder.button8);
buttons.add(viewHolder.button9);
buttons.add(viewHolder.button10);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mQuestionTextView.setText(questionHint.get(position).getValue0());
viewHolder.mHintTextView.setText(questionHint.get(position).getValue1());
Votes item = getItem(position);
int count = 0;
double score = 0;
for(int i = 0; i<item.getAll().size(); i++){
score += (i+1) * item.getAll().get(i);
count +=item.getAll().get(i);
}
if(count>0){
score = score/count;
}
if(score==0){
score = 10;
}
// double diff = (10-Math.round(score));
colorButton(Math.round(score), viewHolder);
// colorButton((int) score);
// for (int j = 9; j >= diff; j--) {
// Button button = buttons.get(j);
// button.setBackgroundColor(Color.WHITE);
// button.setTextColor(Color.BLACK);
// }
}
return convertView;
}
private void colorButton(long givenMark, ViewHolder viewHolder){
for(int i=0; i<buttons.size();i++){
buttons.get(i).setBackgroundColor(Color.WHITE);
}
for (int j = 0; j <= givenMark; j++) {
Button button = buttons.get(j);
button.setBackgroundColor(Color.parseColor(colors.get(j)));
}
}
private static class ViewHolder {
TextView mQuestionTextView;
TextView mHintTextView;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button button10;
}
}
It looks like this:
So, when I press button 3, all colors beyond 3, must become white. Or when I press button 9, all buttons before it must have its colors, and buttons in fron of it must be white. But this does not happen, and there is no error.
Thank you for any help.
Isn't that rating bar?
OnClickListener is wrong, I meant not the right listener, you got the idea wrong. What's the enclosing View?