A had a custom ListView recently. Then I had to display all the list items without scrollbar. Following the method to place items in LinearLayout I changed my code but I can't bind onClickListener to new layout. In ListView I used position var to determine what view was touched. But in LinearLayout onClick callback hasn't position parameter.
Here is my BasketActivity.class:
package ru.**.**;
public class BasketActivity extends Activity {
ArrayList<Item> items = new ArrayList<Item>();
SQLiteDatabase database;
Map<String, ?> all;
ItemAdapter adapter;
Item item2delete;
View deletingView;
private SharedPreferences settings;
private SharedPreferences settings2;
private Basket basket;
TextView basketSum;
private int position2delete;
private Map<String, ?> all2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basket);
<..cutted..>
settings = getSharedPreferences("basket", 0);
settings2 = getSharedPreferences("price", 0);
basket = new Basket(settings, settings2);
all = basket.getList();
LinearLayout l1 = (LinearLayout) findViewById(R.id.l1);
MyDBAdapter myDBAdapter = new MyDBAdapter(getBaseContext());
myDBAdapter.open();
Cursor itemCursor = myDBAdapter.getItemsInBasket(all);
while (itemCursor.moveToNext()) {
String[] columns = itemCursor.getColumnNames();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]);
}
Item item = new Item();
item.setId(itemCursor.getString(0));
item.setArticul(itemCursor.getString(MyDBSchema.ITEM_ARTICUL));
item.setTitle(itemCursor.getString(MyDBSchema.ITEM_TITLE));
item.setPrice(itemCursor.getInt(MyDBSchema.ITEM_PRICE));
item.setPic80(itemCursor.getString(MyDBSchema.ITEM_PIC80));
item.setPic300(itemCursor.getString(MyDBSchema.ITEM_PIC300));
item.setMessage(itemCursor.getString(MyDBSchema.ITEM_MESSAGE));
item.setColor(itemCursor.getString(MyDBSchema.ITEM_COLOR));
item.setColorpos(itemCursor.getString(MyDBSchema.ITEM_COLORPOS));
items.add(item);
}
itemCursor.close();
myDBAdapter.close();
for (int position=0; position<items.size(); position++) {
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.list_basket, null);
final Item i = items.get(position);
if (i != null) {
Item ei = (Item) i;
final TextView title = (TextView) v.findViewById(R.id.title);
if (title != null) title.setText(ei.title);
final TextView articul = (TextView) v.findViewById(R.id.articul);
if (articul != null) articul.setText(ei.articul);
TextView payed = (TextView) v.findViewById(R.id.payed);
if (payed != null) payed.setVisibility(TextView.GONE);
TextView status = (TextView) v.findViewById(R.id.status);
if (status != null) status.setVisibility(TextView.GONE);
Context context = getBaseContext();
ProgressBar p = new ProgressBar(context);
p.setIndeterminate(true);
Drawable d = p.getIndeterminateDrawable();
WebImageView wiv = (WebImageView) v.findViewById(R.id.pic80);
wiv.setImageWithURL(context, ei.pic80, d);
final TextView price = (TextView) v.findViewById(R.id.price);
if (price != null) price.setText(ei.price_valid);
final TextView quant = (TextView) v.findViewById(R.id.quant);
if (quant != null) {
int q = (Integer) all.get(ei.articul);
if (q > 1) {
quant.setText("x "+q+" шт.");
}
}
}
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
deletingView = v;
int position = 0; //The order number of the view should be here!
Item item = (Item) items.get(position);
item2delete = item;
position2delete = position;
AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
builder.setMessage(getString(R.string.suredelete))
.setCancelable(false)
.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BasketActivity.this.removeItem();
deletingView.setVisibility(View.GONE);
}
})
.setNegativeButton(getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
l1.addView(v);
}
basketSum = (TextView) findViewById(R.id.basketsum);
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
}
protected void removeItem() {
basket.remove(item2delete);
Context context = getApplicationContext();
CharSequence text = getText(R.string.item_deleted);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
+ basket.getBasketPriceValid() + "</b>"));
items.remove(position2delete);
}
}
My question is how to get view's position at onClick(View v)?
You can use the View's tag;
for (int position=0; position<items.size(); position++) {
v.setTag(position);
}
and in the onClick(View v)
public void onClick(View v) {
int position = 0;
if (v.getTag() instanceof Integer) {
position = (Integer) v.getTag();
}
}
Can you have
v.setTag(items.get(position).getId();
and then in onClick
public void onClick(View v) {
int id= v.getTag();
}
Related
I am developing an android app for Restaurant Ordering system, Now I want to add some Description for the particular Item so that I had added the Dialogfragment and set it to the Custom Adapter ImageView Click listener, the dialog fragment showing correctly, as well as data, is also passing from edit text, but it shows in the last element of the listview.
I had tried various procedures and method but it still getting the same please help me, guys.
I am attaching the screen shots of my project
New TABLE ACTIVITY WHERE IS LISTVIEW
DIALOG FRAGMENT
AFTER ADDING DIALOG FRAGMENT DATA
Here I am Adding Custom Adapter Code
public class CustomAdapter_MenuList extends BaseAdapter{
Activity activity;
Context CONTEXT;
LayoutInflater layoutInflater;
public List<GetandSet> details;
CustomAdapter_MenuList.ViewHolder viewHolder;
GetandSet getandSet;
TextView GrandTotal;
TextView txtTotalItems;
ArrayList<String>Desciption = new ArrayList<>();
private EditText mInput;
Button btnadd,btnclose;
String desc;
public CustomAdapter_MenuList(Activity activity,Context context, List<GetandSet> details,TextView txtGrandtotal,TextView txttotalitems) {
this.activity = activity;
this.CONTEXT = context;
this.details = details;
this.GrandTotal = txtGrandtotal;
this.txtTotalItems = txttotalitems;
this.layoutInflater = (LayoutInflater) LayoutInflater.from(context);
}
#Override
public int getCount() {
return details.size();
}
#Override
public Object getItem(int position) {
return details.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
getandSet = new GetandSet();
final float menu_rate =
Float.parseFloat(details.get(position).getRate());
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater)CONTEXT.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newtable_template, null);
viewHolder = new CustomAdapter_MenuList.ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (CustomAdapter_MenuList.ViewHolder) convertView.getTag();
}
for(int i = 0 ; i<details.size(); i++)
{
for(int j = i+1; j < details.size(); j++)
{
if(details.get(j).getMenu_id().equals(details.get(i).getMenu_id()))
{
details.remove(j);
j--;
getandSet = details.get(i);
getandSet.Menu_qty = details.get(i).getMenu_qty() + 1;
}
}
}
viewHolder.txtsrno.setText(details.get(position).getMenu_id());
viewHolder.txtsrno.setVisibility(View.INVISIBLE);
viewHolder.txtsrnotem.setText(String.valueOf(position+1));
viewHolder.txtmname.setText(details.get(position).getM_name());
viewHolder.txtrate.setText(details.get(position).getRate());
getandSet = details.get(position);
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(getandSet.Menu_qty+"");
viewHolder.txtprice.setText(getandSet.Menu_price +"");
GrandTotal.setText(String.valueOf(grandTotal(details)));
txtTotalItems.setText(String.valueOf(grandTotal(details,position)));
notifyDataSetChanged();
//Add Button Code
viewHolder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, 1);
getandSet.Menu_qty = getandSet.Menu_qty + 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
});
//Minus Button
viewHolder.btnsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, -1);
if(getandSet.Menu_qty > 1)
{
getandSet.Menu_qty = getandSet.Menu_qty - 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty ;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
}
});
//Add Description Button
viewHolder.btn_Desc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(position);
}
});
return convertView;
}
//View Holder Class
private class ViewHolder {
TextView txtsrno,txtmname, txtqty,txtrate,txtprice,txtsrnotem,txtdesc;
Button btnadd,btnsub;
ImageView btn_Desc;
public ViewHolder(View view)
{
txtsrno = (TextView)view.findViewById(R.id.txt_NTsrno);
txtsrnotem = (TextView)view.findViewById(R.id.txt_NT_srno);
txtmname = (TextView)view.findViewById(R.id.txt_NT_Item);
txtqty = (TextView)view.findViewById(R.id.txt_Nt_qty);
txtrate = (TextView)view.findViewById(R.id.txt_Nt_rate);
txtprice = (TextView)view.findViewById(R.id.txt_NT_price);
txtdesc = (TextView)view.findViewById(R.id.txt_NT_desc);
btnadd = (Button)view.findViewById(R.id.btn_add);
btnsub = (Button)view.findViewById(R.id.btn_sub);
btn_Desc = (ImageView) view.findViewById(R.id.img_desc);
}
}
//Grand - Total
private float grandTotal(List<GetandSet> items){
float totalPrice = 0;
for(int i = 0 ; i < items.size(); i++) {
totalPrice += items.get(i).getMenu_price();
}
return totalPrice;
}
//Number of Items
private int grandTotal(List<GetandSet> items,int p){
int totalitems = 0;
for(int i = 0 ; i < items.size(); i++) {
totalitems += 1;
}
return totalitems;
}
private void openDialog(final int position){
LayoutInflater inflater = LayoutInflater.from(activity);
View subView = inflater.inflate(R.layout.dialogfragment_description, null);
mInput = subView.findViewById(R.id.edt_desc);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Description");
builder.setView(subView);
final AlertDialog alertDialog = builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
desc = mInput.getText().toString();
//getandSet = details.get(position);
details.get(position).setDes(desc);
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
builder.show();
}
}
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
Just put this lines after completion of openDialog() method
I am working on an app in android studio.
My app has a listview, whiche has Edittext , textview and checkbox in its row.
my proplem is when I have more than five items in my listvew, the listview lost focus, for example: when I press on checkbox on the 6th item , the textview shows me the name from the first item.
I wish I could explain my proplem very well.
This is my adapter:
public AdapterListView(Context context, int resource, ArrayList<ObjectPeople> arraypeople) {
super(context, resource);
this.mContext = context;
this.arrayPeople = arraypeople;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.mission_name = (TextView) convertView.findViewById(R.id.mission_name);
holder.mission_time = (TextView) convertView.findViewById(R.id.mission_time);
holder.edit_time = (EditText) convertView.findViewById(R.id.edit_time);
holder.mission_image= (ImageView) convertView.findViewById(R.id.mission_image);
holder.cbm = (CheckBox) convertView.findViewById(R.id.checkbo);
convertView.setTag(holder);
holder.cbm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v ) {
CheckBox cb = (CheckBox) v ;
final ObjectPeople person = arrayPeople.get(position);
if(cb.isChecked()) {
arrayPeople.get(position).checkbox= true;
int mis_tm=0;
try{ mis_tm= Integer.parseInt( holder.edit_time.getText().toString());}
catch (Exception e){
cb.setChecked(false);
Toast.makeText(mContext, "يرجى إدخال قيمة معينة", Toast.LENGTH_SHORT).show();}
person.time= mis_tm;
if(mis_tm>0&&mis_tm<1200){
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: "+ person.time );
holder.edit_time.setVisibility(View.GONE);}
else{
cb.setChecked(false);
Toast.makeText(mContext, "يرجى اختيار رقم حقيقي", Toast.LENGTH_SHORT).show();
}
}
else {
arrayPeople.get(position).checkbox= false;
holder.edit_time.setVisibility(View.VISIBLE);
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
final ObjectPeople person = arrayPeople.get(position);
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: ");
holder.mission_image.setImageResource(arrayPeople.get(position).image);
holder.edit_time.setId(position);
holder.edit_time.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
try {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayPeople.get(position).time = Integer.parseInt(Caption.getText().toString());
}
}catch (Exception e){}
}
});
holder.cbm.setTag(arrayPeople);
return convertView;
}
#Override
public int getCount() {
return arrayPeople.size();
}
static class ViewHolder {
TextView mission_name;
TextView mission_time;
EditText edit_time;
ImageView mission_image;
CheckBox cbm;
}
}
and this select.java which contains the arraylist and list view:
public class select extends AppCompatActivity {
ArrayList<ObjectPeople> arrPeople;
ListView lvPeople;
AdapterListView adapter;
ObjectPeople person;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
settings = getApplicationContext().getSharedPreferences("shared", 0);
lvPeople= (ListView) findViewById(R.id.lvPeopl);
arrPeople=new ArrayList<>();
person = new ObjectPeople("حفظ قرآن", 0,false, R.drawable.quran_hifz_r);
arrPeople.add(person);
person = new ObjectPeople("تلاوة قرآن", 0 ,false,R.drawable.img);
arrPeople.add(person);
person = new ObjectPeople("قراءة كتاب", 0 , false,R.drawable.books_r);
arrPeople.add(person);
person = new ObjectPeople("دورات تطوير مهارات", 0 , false,R.drawable.courses_r);
arrPeople.add(person);
person = new ObjectPeople("رياضة", 15 , false,R.drawable.sport_r);
arrPeople.add(person);
final String[] misson_name = new String[1];
Button adf= (Button) findViewById(R.id.add_mission_out_btn);
adf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(select.this).inflate(R.layout.add_mission_lyt,null);
final EditText add_name = (EditText) view.findViewById(R.id.add_mission_name);
AlertDialog.Builder builder = new AlertDialog.Builder(select.this);
builder.setMessage("add your mission")
.setView(view)
.setPositiveButton("إضافة", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
misson_name[0] = add_name.getText().toString();
arrPeople.add(new ObjectPeople(misson_name[0], 0, true,R.drawable.smile_small_r));
}
})
.setNegativeButton("إلغاء",null)
.setCancelable(false);
AlertDialog alert =builder.create();
alert.show();
}
});
adapter=new AdapterListView(this,R.layout.item_listview,arrPeople);
lvPeople.setAdapter(adapter);
checkButtonClick();
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.btn_save);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", 0);
int hours2=settings.getInt("hours",0)*60;
ArrayList<ObjectPeople> selected_missions = new ArrayList<>();
int missoins_time_calc=0;
for (int i = 0; i <arrPeople.size(); i++) {
if(arrPeople.get(i).checkbox==true){
selected_missions.add(arrPeople.get(i));
missoins_time_calc= missoins_time_calc + arrPeople.get(i).time;}
}
if (hours2 == missoins_time_calc){
Gson gson = new Gson();
String jsonText = gson.toJson(selected_missions);
SharedPreferences.Editor editor = settings.edit();
editor.putString("selected_array", jsonText);
editor.commit();
Intent intent = new Intent(select.this, yourprogram.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
else if (hours2 > missoins_time_calc){
Toast.makeText(select.this, "بقي"+(-missoins_time_calc+ hours2)+" دقيقة ", Toast.LENGTH_SHORT).show();}
else if (hours2< missoins_time_calc){
Toast.makeText(select.this,"يوجد "+ (-hours2+missoins_time_calc)+" دقيقة زيادة على الوقت المخصص", Toast.LENGTH_SHORT).show();
}
/* ArrayList<missions> missionsList = dataAdapter.missionsList;
for(int i = 0; i< missionsList.size(); i++){
missions missions = missionsList.get(i);
if(missions.isSelected()){}}*/
}
});
}
}
I think the error is the way your arrayPeople List is being populated, if you say the sixth item gets you the first you can try reversing the order with
Collections.reverse(arrayPeople);
you can place this line of code below your holder.cbm.setOnClickListener on your adapter
Hope it helps.
I have a listview in which list item's background highlights while a notification arrives but the problem is that when I scroll the list then items changes highlighting. Suppose initially first item was listed when I scroll down then another item highlights. I have also used notifysetdatachanged.
Code for List Activity
public class NewPageActivity extends Fragment{
// this is my notification code when notifcation arrives
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(
"unique_name");
mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
String msg_for_me = intent.getStringExtra("message");
//log our message value
Log.e("TAG", "onReceive: boradcast" + msg_for_me);
if (msg_for_me.contains("&")) {
String msg1[] = msg_for_me.split("&");
if (msg1[0].contains("Waiting for acceptance...")) {
edit.putInt("newTabHighlight", sp.getInt("newTabHighlight", 0) + 1);
edit.putString("newOrder", sp.getString("newOrder", null) + "&" + msg1[1].split("=")[1]);
edit.putInt("reminderTab", sp.getInt("reminderTab", 0) + 1);
edit.putInt("newOrderCount", 1);
edit.commit();
connectToDatabase();
}
}
// code for when get data through web service and set adapter
if(getActivity()!= null) {
adapter = new customadapetr_new(dataModels, getActivity(), NewPageActivity.this);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
setListViewHeightBasedOnChildren(list);
}
}
// code for adapter where background highlights
private void setNewCardBackground(final String Order_id, final RelativeLayout MenuCard, String OrderFlag)
{
Log.e("TAG", "setNewCardBackground: " );
newOrder = sp.getString("newOrder", "null");
if (newOrder.contains("&")) {
newOrderArray = newOrder.split("&");
Log.e("TAG", "setNewCardBackground:order "+newOrderArray);
for (int i = 0; i < newOrderArray.length; i++) {
if (Order_id.equals(newOrderArray[i])) {
MenuCard.setBackgroundResource(R.drawable.highlightedorder);
MenuCard.setPadding(20,10,20,10);
newOrderlength++;
break;
}
// custom adapter get view code
#Override
public View getView(final int position, View vv, ViewGroup parent) {
menuModels= new ArrayList<>();
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
final DataModel data=dataSet.get(position);
if (vv == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
vv = inflater.inflate(R.layout.adapter_listview_newpage_card, parent, false);
viewHolder.rupee=(TextView)vv.findViewById(R.id.rupee);
viewHolder.dateandtime=(TextView)vv.findViewById(R.id.dateandtime);
viewHolder.modeofpayment=(TextView)vv.findViewById(R.id.modeofpayment);
viewHolder.location=(TextView)vv.findViewById(R.id.location);
viewHolder.customerName=(TextView)vv.findViewById(R.id.customerName);
viewHolder.orderId = (TextView)vv.findViewById(R.id.orderId);
viewHolder.order_time = (TextView) vv.findViewById(R.id.order_time);
viewHolder.menucard = (RelativeLayout) vv.findViewById(R.id.menucard);
viewHolder.accept = (ImageView) vv.findViewById(R.id.accept);
viewHolder.statustext = (TextView)vv.findViewById(R.id.statustext);
viewHolder.orderstatus = (TextView) vv.findViewById(R.id.orderstatus);
viewHolder.order_card_layout =(RelativeLayout) vv.findViewById(R.id.order_card_layout);
viewHolder.progressBar = (PlayGifView) vv.findViewById(R.id.progressBar);
viewHolder.progressBar.setImageResource(R.drawable.renewedloader);
viewHolder.showhide =(ImageView) vv.findViewById(R.id.showhide);
viewHolder.comments = (TextView) vv.findViewById(R.id.comments);
viewHolder.expanded_menulist =(ListView) vv.findViewById(R.id.menulist1);
viewHolder.expanded_menulist.setVisibility(View.GONE);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
height = metrics.heightPixels;
width = metrics.widthPixels;
sp =mContext.getSharedPreferences("afewtaps", Context.MODE_PRIVATE);
face = Typeface.createFromAsset(mContext.getAssets(), "fonts/Nunito-Regular.ttf");
face1 = Typeface.createFromAsset(mContext.getAssets(), "fonts/Rupee_Foradian_2.ttf");
int size = dataSet.size();
String menu=data.getMenu();
viewHolder.listview=(ListView)vv.findViewById(R.id.menulist);
setListViewHeightBasedOnChildren(viewHolder.listview);
String paynt = data.getPaymemt_method();
final String order_id = data.getOrder_id();
final String Order_flag = data.getOrder_flag();
setNewCardBackground(order_id, viewHolder.menucard,Order_flag );
String orderEscalation = data.getOrder_escalated();
setEscalation(viewHolder.statustext, viewHolder.accept, viewHolder.orderstatus, order_id, orderEscalation);
int time = Integer.parseInt(data.getTimer_time());
setTime(time, viewHolder.order_time);
// menucard item
comment_value = data.getOrder_comments();
viewHolder.accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeListItem(viewHolder.order_card_layout, position);
objNewPageActivity.SendOrder(data.getOrder_id());
}
});
viewHolder.customerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCustomerProfile(order_id, mContext);
}
});
try {
JSONArray jsonArray1 = new JSONArray(menu);
String orderMenu[][] = new String[jsonArray1.length()][4];
int j;
for (j = 0; j < jsonArray1.length(); j++) {
menumodel = new MenuItemModel();
JSONObject ob2 = jsonArray1.getJSONObject(j);
// String menu_name, menu_qty, menu_price;
String menu_veg_type = ob2.getString("type");
menumodel.setMenuitem_type(menu_veg_type);
String menu_name = ob2.getString("item");
menumodel.setMenuitem_name(menu_name);
String menu_qty = ob2.getString("qty");
menumodel.setMenuitem_qty(menu_qty);
String menu_price = ob2.getString("price");
menumodel.setMenuitem_price(menu_price);
menuModels.add(menumodel);
}
viewHolder.listview.setAdapter(new MyAdapter(mContext,menuModels));
setListViewHeightBasedOnChildren(viewHolder.listview);
viewHolder.expanded_menulist.setAdapter(new Expanded_Menu_Adapter(mContext,menuModels));
//setListViewHeightBasedOnChildren(viewHolder.expanded_menulist);
}catch (Exception e)
{
}
int menuArrayLenghth = menuModels.size();
if(menuArrayLenghth > 2)
{
viewHolder.showhide.setVisibility(View.VISIBLE);
}
else
{
viewHolder.showhide.setVisibility(View.GONE);
}
result=vv;
vv.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) vv.getTag();
result=vv;
}
lastPosition = position;
viewHolder.dateandtime.setText(data.getOrder_time());
viewHolder.modeofpayment.setText(data.getPaymemt_method());
viewHolder.location.setText(data.getCustomer_location());
// amount
String amounttext = "` " + data.getPrice();
SpannableStringBuilder mySpannable = new SpannableStringBuilder(amounttext);
mySpannable.setSpan(new CustomTypefaceSpan("", face1), 0, 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
mySpannable.setSpan(new CustomTypefaceSpan("", face), 2, data.getPrice().length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
viewHolder.rupee.setText(mySpannable);
viewHolder.customerName.setText(data.getCustomer_name());
viewHolder.orderId.setText(data.getOrder_id());
if(!(comment_value.equals("0"))){
viewHolder.comments.setVisibility(View.VISIBLE);
viewHolder.comments.setText(data.getOrder_comments());
}
else
{
viewHolder.comments.setVisibility(View.GONE);
}
viewHolder.showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewHolder.listview.getVisibility() == View.VISIBLE)
{
viewHolder.expanded_menulist.setVisibility(View.VISIBLE);
viewHolder.listview.setVisibility(View.GONE);
viewHolder.showhide.setImageResource(R.drawable.blackarrrowup);
if(!(comment_value.equals("0"))){
viewHolder.comments.setVisibility(View.VISIBLE);
viewHolder.comments.setText(data.getOrder_comments());
}
else
{
viewHolder.comments.setVisibility(View.GONE);
}
}
else if(viewHolder.expanded_menulist.getVisibility() == View.VISIBLE) {
viewHolder.expanded_menulist.setVisibility(View.GONE);
viewHolder.listview.setVisibility(View.VISIBLE);
viewHolder.showhide.setImageResource(R.drawable.blackarrow);
viewHolder.comments.setVisibility(View.GONE);
}
}
});
return vv;
}
The problem could be caused by Views being recycled by the Adapter: when you scroll down/up the highlighted View gets recycled and used at another position in the ListView. You could set the background color of each View to the default color in your adapter's getView. This way the backround color of the recycled View will be set to back to normal before it's displayed again.
this is my first post, and I have a doubt about a listview item management, I have seen some post about recycleView, but I don´t understand yet how to implement it in my problem.
Well, I've got a listView that shows some elements like a shopping car where the user clicks the button autorizarDetalleSolicitud, which opens an alertDialog where an user choices a wished amount of that respective item, so if the amount is bigger than zero, the checkbox changes to state TRUE, but when I test this function, I could see that other checkBoxes are activated (or changes to state TRUE) randomly; i.e. When I input an amount to first item, the state of penultimate checkBox changes to TRUE. Thanks for your attention.
//Button of each listview item
public void autorizarDetalleSolicitud(View v) {
LinearLayout layoutboton = (LinearLayout) v.getParent();
checkBoxelemento = (CheckBox) layoutboton.getChildAt(0);
RelativeLayout relativeLayout = (RelativeLayout) layoutboton.getParent();
TableLayout tableLayout = (TableLayout) relativeLayout.getChildAt(1);
TextView tipoelementotextview = (TextView) tableLayout.findViewById(R.id.tipoelem);
TextView unidadelem = (TextView) tableLayout.findViewById(R.id.unidadelem);
TextView idelem = (TextView) tableLayout.findViewById(R.id.idelem);
TextView cantpedida = (TextView) tableLayout.findViewById(R.id.cantidadelem);
cantautorizadatextview = (TextView) tableLayout.findViewById(R.id.cantautorizado);
final String tipoelemento = tipoelementotextview.getText().toString();
cantidadpedida = Double.parseDouble(cantpedida.getText().toString());
cantidadautorizada = Double.parseDouble(cantautorizadatextview.getText().toString());
idelemento = idelem.getText().toString();
// configura el alert dialog
builder = new AlertDialog.Builder(this);
builder.setMessage(unidadelem.getText() + " a autorizar:");
builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
if (tipoelemento.equals("Material")) {
numberPickerCantidad = new NumberPicker(getApplicationContext());
numberPickerCantidad.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
numberPickerCantidad.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
String[] nums = new String[100];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.toString(i);
}
numberPickerCantidad.setMinValue(0);
numberPickerCantidad.setMaxValue(nums.length - 1);
numberPickerCantidad.setWrapSelectorWheel(false);
numberPickerCantidad.setDisplayedValues(nums);
if(cantidadautorizada==0){
numberPickerCantidad.setValue(cantidadpedida.intValue());
}else{
numberPickerCantidad.setValue(cantidadautorizada.intValue());
}
builder.setPositiveButton(R.string.agregar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int cantidadautorizada = numberPickerCantidad.getValue();
autorizarCantidad((double)cantidadautorizada,tipoelemento);
}
});
builder.setView(numberPickerCantidad);
} else {
cantreactivosoli = new EditText(getApplicationContext());
cantreactivosoli.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
cantreactivosoli.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
cantreactivosoli.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
if(cantidadautorizada==0){
cantreactivosoli.setText(cantidadpedida + "");
}else{
cantreactivosoli.setText(cantidadautorizada + "");
}
cantreactivosoli.setText(cantidadpedida + "");
builder.setView(cantreactivosoli);
builder.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String cantidadedittext = cantreactivosoli.getText().toString();
if (!cantidadedittext.equals("")) {
Double cantidadingresada = Double.parseDouble(cantidadedittext);
autorizarCantidad(cantidadingresada,tipoelemento);
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_sincantidad, Toast.LENGTH_SHORT);
toast.show();
}
}
});
builder.setView(cantreactivosoli);
}
builder.show();
}
// Method that saves the input value in an arraylist and implements a setCheck(true) of that itemstrong text
public void autorizarCantidad(Double cantidadingresada, String tipoelemento){
if (cantidadingresada <= cantidadpedida) {
int flag = 0;
for (int indice = 0; indice < elementosrevisados.size(); indice++) {
if (elementosrevisados.get(indice).getId().equals(idelemento)) {
elementosrevisados.get(indice).setCantidadAutorizada(cantidadingresada+"");
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
cantidadpedida = cantidadingresada;
flag=1;
break;
}
}
if(flag==0) {
Elemento elem = new Elemento(idelemento, cantidadpedida + "", cantidadingresada + "");
elementosrevisados.add(elem);
checkBoxelemento.setChecked(true);
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
}
for(int i=0;i<elementosrevisados.size();i++){
Log.e("Elemento revisado: ",elementosrevisados.get(i).toString());
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_cantidadautorizada, Toast.LENGTH_SHORT);
toast.show();
}
}
SOLUTION!
To solve my problem, I based on this answer recording an array with positions of the checkboxes verifying if they were checked, I mean, this a boolean array, and each checkbox has a status TRUE or FALSE. Thanks to #AnshulTyagi
public class ElementoAdapter extends BaseAdapter {
private ArrayList<Boolean> status = new ArrayList<Boolean>();
private static LayoutInflater inflater = null;
private ArrayList<HashMap<String, String>> data;
Activity activity;
CompoundButton.OnCheckedChangeListener miCheckedListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkBoxView,boolean isChecked){
int posicioncheck = (Integer)checkBoxView.getTag();
if (checkBoxView.isChecked()) {
status.set(posicioncheck,true);
} else {
status.set(posicioncheck,false);
}
}
};
public ElementoAdapter(Activity activity, ArrayList<HashMap<String, String>> data){
this.activity = activity;
this.data = data;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < data.size(); i++) {
status.add(false);
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View vista = convertView;
ViewHolder holder;
if (vista == null) {
vista = inflater.inflate(R.layout.listitem_elemento,null);
holder = new ViewHolder();
holder.labelIdElemento = (TextView) vista.findViewById(R.id.labelIdElemento);
holder.idElemento = (TextView) vista.findViewById(R.id.idelem);
holder.labelTipo = (TextView) vista.findViewById(R.id.labelTipoElemento);
holder.tipoElemento = (TextView) vista.findViewById(R.id.tipoelem);
holder.labelCodigoElemento = (TextView) vista.findViewById(R.id.labelCodigo);
holder.codigoElemento = (TextView) vista.findViewById(R.id.codigoelem);
holder.labelDescripcionElemento= (TextView) vista.findViewById(R.id.labelDescripcion);
holder.descripcionElemento = (TextView) vista.findViewById(R.id.descripcionelem);
holder.labelMarcaElemento = (TextView) vista.findViewById(R.id.labelMarca);
holder.marcaElemento = (TextView) vista.findViewById(R.id.marcaelem);
holder.labelUnidadMedida = (TextView) vista.findViewById(R.id.labelUnidadMedida);
holder.unidadMedida = (TextView) vista.findViewById(R.id.unidadelem);
holder.checkBoxElemento = (CheckBox) vista.findViewById(R.id.checkBox);
holder.botonElemento = (Button) vista.findViewById(R.id.botonsolic);
vista.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// remove the listener so that it does not get attached to other chechboxes.
holder.checkBoxElemento.setOnCheckedChangeListener(null);
holder.checkBoxElemento.setChecked(status.get(position));
Log.e("check "+position,status.get(position)+"");
}
holder.idElemento.setText(data.get(position).get("idelemento"));
holder.tipoElemento.setText(data.get(position).get("tipoelemento"));
holder.codigoElemento.setText(data.get(position).get("codigoelemento"));
holder.descripcionElemento.setText(data.get(position).get("descripcionelemento"));
holder.marcaElemento.setText(data.get(position).get("marcaelemento"));
holder.unidadMedida.setText(data.get(position).get("unidadmedida"));
Log.e("idelemento creado ",data.get(position).get("idelemento"));
holder.checkBoxElemento.setTag(position);
//add a custom listener
holder.checkBoxElemento.setOnCheckedChangeListener(miCheckedListener);
return vista;
}
static class ViewHolder {
TextView labelIdElemento;
TextView idElemento;
TextView labelTipo;
TextView tipoElemento;
TextView labelCodigoElemento;
TextView codigoElemento;
TextView labelDescripcionElemento;
TextView descripcionElemento;
TextView labelMarcaElemento;
TextView marcaElemento;
TextView labelUnidadMedida;
TextView unidadMedida;
CheckBox checkBoxElemento;
Button botonElemento;
}
}
I have a listView of items.Each item has two separate fragment inside it and gets visible when the item is clicked. Inside a fragment there is another ListView and a button. The button displays a dialog through which ListView inside the fragment gets populated.The problem is when the dialog closes,the parent listview gets refreshed and as a result fragment visibility is gone. I have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed. So someone please help me in it.
The following is my parent listView class:
#SuppressLint("NewApi")
public class Due extends FragmentActivity implements
OutletformAddDialog_due.DonebuttonListener {
TextView headerView;
View tempstore, imagetempstore;
OutletformAddDialog_due selectedOutlet;
Fragment fr;
public BaseAdapter dueadapter;
ListView Duelist;
Boolean DuedetailFlag = false, OrderdetailFlag = false;
TextView DueDetailsRight, DueDetailsTop, DueDetailsBottom,
DueDetailsrightHorizontal, OrderDetailsleft, OrderDetailstop,
OrderDetailsBottom, OrderDetailsleftHorizontal, DueDetailsButton,
OrderDetailsButton, btnDueNav, tvOutletName;
Button DuetoCallCard;
int index;
public int getIndex() {
return index;
}
private String order_id;
private String outlet_id;
private String amount;
private String date;
private int count = 0;
private View lvNavigation;
boolean formDashboard = false;
ArrayList<Payment> dueArray = new ArrayList<Payment>();
ArrayList<DueItem> tempdueArray = new ArrayList<DueItem>();
ArrayList<String> navigationList;
NavigationAdapter adapter;
int prevItem, currentItem;
View btnDuetoCallCard;
private ImageView home;
String stateStore = "";
TextView totalCollectedDue;
TextView orderDueAmmount;
ViewGroup header;
private View clickedHeaderView;
FragmentManager fm;
FragmentTransaction fragmentTransaction;
public String getheaderDueamount() {
return orderDueAmmount.getText().toString();
}
public void setheaderDueamount(String amount) {
orderDueAmmount.setText(amount);
}
// public void setDueList(int position) {
// dueadapter.getItem(position)
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.duea_amount_layout);
DuetoCallCard = (Button) findViewById(R.id.btnDuetoCallCard);
DuetoCallCard.bringToFront();
Duelist = (ListView) findViewById(R.id.due_layout_listView);
tvOutletName = (TextView) findViewById(R.id.textviewoutletname);
home = (ImageView) findViewById(R.id.btndueHome);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(new Intent(Due.this,
MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
}
});
Bundle b = getIntent().getExtras();
if (b != null) {
formDashboard = getIntent().getExtras().getBoolean("fromDashboard");
}
if (formDashboard) {
// spinRoute.setVisibility(View.VISIBLE);
// spinOutlet.setVisibility(View.VISIBLE);
// Outlet1542
selectedOutlet = new OutletformAddDialog_due();
selectedOutlet.show(getFragmentManager(), "dialog");
} else {
populateArray();
}
btnDuetoCallCard = findViewById(R.id.btnDuetoCallCard);
initArrays();
// for disappearing the big circular button
Duelist.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
// End has been reached
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_out));
btnDuetoCallCard.setVisibility(View.GONE);
} else {
// btnaddOutlet.startAnimation(AnimationUtils.loadAnimation(Outlet_List.this,
// android.R.anim.fade_in));
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
if (visibleItemCount == totalItemCount)
btnDuetoCallCard.setVisibility(View.VISIBLE);
}
});
}
void populateArray() {
dueadapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(R.layout.dueamounts_list_item,
null);
// }
TextView orderNo = (TextView) convertView
.findViewById(R.id.tvdueOrderNo);
TextView orderDate = (TextView) convertView
.findViewById(R.id.tvdueDate);
orderDueAmmount = (TextView) convertView
.findViewById(R.id.tvRemainingDueAmmount);
ImageButton imgbtn = (ImageButton) convertView
.findViewById(R.id.dueImageButton);
orderNo.setText("Order "
+ dueArray.get(position).getOrder_id().getId());
orderDate.setText(dueArray.get(position).getDate());
Double dueAmount = dueArray.get(position).getAmount();
orderDueAmmount.setText(formatDoubleValues(dueAmount));
// old way
// orderNo.setText("" + dueArray.get(position).getOrder());
// orderDate.setText(dueArray.get(position).getDate());
// orderAmmount.setText(dueArray.get(position).getAmmount());
header = (ViewGroup) convertView.findViewById(R.id.header);
header.setId(position);
header.setOnClickListener(due_header_clicked);
ViewGroup body = (ViewGroup) convertView
.findViewById(R.id.body);
View Headerparent = (View) header.getParent();
View image = findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
// imgbtn.setOnClickListener(due_header_clicked);
View placeHolder = convertView
.findViewById(R.id.duefragment_placeholder);
int id = 10000 + position;
placeHolder.setId(id);
dueArray.get(position).setPlaceHolder(id);
Payment item = dueArray.get(position);
if (stateStore.equals("" + position)) {
// header.performClick();
body.setVisibility(View.VISIBLE);
header.performClick();
} else {
body.setVisibility(View.GONE);
}
// totalCollectedDue = (TextView) convertView
// .findViewById(R.id.tvTotalCollectedDueAmount);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return dueArray.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dueArray.size();
}
};
Duelist.setAdapter(dueadapter);
dueadapter.notifyDataSetChanged();
Duelist.setDivider(null);
Duelist.setDividerHeight(0);
}
int headerIndex = 0;
// View headerView;
int placeHolder_id = 0;
public OnClickListener due_header_clicked = new OnClickListener() {
#Override
public void onClick(View v) {
onHeaderClicked(v);
clickedHeaderView = v;
}
};
public void onHeaderClicked(View v) {
index = v.getId();
headerIndex = index;
// fr = dueArray.get(index).getDueFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
fr = tempdueArray.get(index).getDueFragment(headerIndex);
// fr.setArguments(bundle);
// tempdueArray.get(index).setDue_fragment(headerIndex);
Due.this.placeHolder_id = dueArray.get(index).getPlaceHolder();
final Payment item = dueArray.get(index);
// saving the header clicked position for later use
stateStore = "" + v.getId();
View view = (View) v.getParent();
TextView headerDueamount = (TextView) view
.findViewById(R.id.tvRemainingDueAmmount);
headerView = headerDueamount;
DueDetailsRight = (TextView) view.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) view.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) view
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) view
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) view.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) view
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) view
.findViewById(R.id.tvDuedetailsrighthorizontal);
final View body = view.findViewById(R.id.body);
View image = view.findViewById(R.id.dueImageButton);
View TAB_Orderdetail = body.findViewById(R.id.btnOrderDetails);
View TAB_Duedetail = body.findViewById(R.id.btnDueDetails);
TAB_Orderdetail.setOnClickListener(change_fragment_listener);
TAB_Duedetail.setOnClickListener(change_fragment_listener);
if (body.getVisibility() != View.VISIBLE) {
if (tempstore != null) {
tempstore.setVisibility(View.GONE);
imagetempstore
.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
}
tempstore = body;
imagetempstore = image;
body.setVisibility(View.VISIBLE);
// if (fr == null) {
View test = (View) v.getParent().getParent();
DueDetailsButton = (TextView) test
.findViewById(R.id.btnOrderDetails);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
// fr = dueArray.get(index).getOrderFragment();
// fragmentTransaction.replace(item.getPlaceHolder(), fr);
// fragmentTransaction.commit();
// fr = dueArray.get(index).getDueFragment();
fr = tempdueArray.get(index).getDueFragment(headerIndex);
fm = getSupportFragmentManager();
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(item.getPlaceHolder(), fr);
fragmentTransaction.commit();
image.setBackgroundResource(R.drawable.ic_expand_icon);
} else {
image.setBackgroundResource(R.drawable.ic_due_dropdown_icon);
body.setVisibility(View.GONE);
}
}
public OnClickListener change_fragment_listener = new OnClickListener() {
#Override
public void onClick(View v) {
changeFargment(v);
}
};
public void changeFargment(View v) {
View test = (View) v.getParent().getParent();
DueDetailsRight = (TextView) test.findViewById(R.id.tvduedetialright);
DueDetailsTop = (TextView) test.findViewById(R.id.tvdeudetailstop);
DueDetailsBottom = (TextView) test
.findViewById(R.id.tvdeudetailsBottom1);
DueDetailsrightHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailslefthorizontal);
OrderDetailsBottom = (TextView) test
.findViewById(R.id.tvorderdetailBottom);
OrderDetailstop = (TextView) test.findViewById(R.id.tvorderdetailtop);
OrderDetailsleft = (TextView) test
.findViewById(R.id.tvOrderdetailsleft);
OrderDetailsleftHorizontal = (TextView) test
.findViewById(R.id.tvDuedetailsrighthorizontal);
DueDetailsButton = (TextView) test.findViewById(R.id.btnDueDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
OrderDetailsButton = (TextView) test.findViewById(R.id.btnOrderDetails);
switch (v.getId()) {
case R.id.btnOrderDetails:
DueDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
OrderDetailsButton.setTextColor(Color.parseColor("#050708"));
// Bundle bundle = new Bundle();
// bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getOrderFragment();
fr = tempdueArray.get(headerIndex).getOrderFragment(headerIndex);
// fr.setArguments(bundle);
DueDetailsRight.setVisibility(View.INVISIBLE);
DueDetailsTop.setVisibility(View.INVISIBLE);
OrderDetailsBottom.setVisibility(View.INVISIBLE);
DueDetailsrightHorizontal.setVisibility(View.INVISIBLE);
OrderDetailsleft.setVisibility(View.VISIBLE);
OrderDetailstop.setVisibility(View.VISIBLE);
DueDetailsBottom.setVisibility(View.VISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnDueDetails:
OrderDetailsButton.setTextColor(Color.parseColor("#8e8f92"));
DueDetailsButton.setTextColor(Color.parseColor("#050708"));
Bundle bundle = new Bundle();
bundle.putInt("index", headerIndex);
// fr = dueArray.get(headerIndex).getDueFragment();
fr = tempdueArray.get(headerIndex).getDueFragment(headerIndex);
fr.setArguments(bundle);
OrderDetailsleft.setVisibility(View.INVISIBLE);
OrderDetailstop.setVisibility(View.INVISIBLE);
DueDetailsBottom.setVisibility(View.INVISIBLE);
OrderDetailsleftHorizontal.setVisibility(View.INVISIBLE);
DueDetailsRight.setVisibility(View.VISIBLE);
DueDetailsTop.setVisibility(View.VISIBLE);
OrderDetailsBottom.setVisibility(View.VISIBLE);
DueDetailsrightHorizontal.setVisibility(View.VISIBLE);
break;
case R.id.btnCollection:
break;
case R.id.btndueHome:
Intent intent = new Intent(new Intent(Due.this, MainActivity.class));
intent.putExtra("home", true);
startActivity(intent);
break;
}
// DueDetail.total = 0;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(Due.this.placeHolder_id, fr);
fragmentTransaction.commit();
}
public void buttonClickActions(View v) {
startActivity(new Intent(Due.this, CallCard.class));
finish();
}
#Override
public void onDoneButtonClick(DialogFragment dialog, String outlet,
String outletId) {
tvOutletName.setText(outlet);
outlet_id = outletId;
populateArray();
}
List<Payment> dueList;
public void initArrays() {
dueList = Entity.query(Payment.class).executeMulti();
// initializing the arraylist with object values
for (int i = 0; i < dueList.size(); i++) {
dueArray.add(dueList.get(i));
DueItem dt = new DueItem();
// dt.setOrder("order " + dueList.get(i).getOrder_id());
// dt.setDate("21July,2015" + dueList.get(i).getDate());
// dt.setAmmount("BDT" + dueList.get(i).getAmount());
tempdueArray.add(dt);
}
}
public String formatDoubleValues(Double myDouble) {
DecimalFormat myFormat = new DecimalFormat("0.00");
return myFormat.format(myDouble);
}
}
And the following class is one of the fragment class that is updating the fragment ListView and the parent Listview it is in.
public class DueDetail extends Fragment {
BaseAdapter dueDetailAdapter;
ListView dueDetailList;
TextView collectionbtn;
TextView totalInitialDue;
CheckBox cbCash, cbCheque;
private String dueAmmount;
double total, totalremainingDue;
int currentDueOnOrder = 100000;
ArrayList<DueCollection> arrayDueDetail = new ArrayList<DueCollection>();
ArrayList<Payment> arrayPayment = new ArrayList<Payment>();
List<DueCollection> duelist;
List<Payment> paymentlist;
private TextView TotalCollectedDue;
Formater fObj = new Formater();
int currentPositon;
int position;
Due dueActivity;
OrderModel om;
DueCollection odi;
boolean setClicked = false;
public DueDetail(int pos) {
//
duelist = Entity.query(DueCollection.class).executeMulti();
for (int i = 0; i < duelist.size(); i++) {
// if (duelist.get(i).getAmount() != null) {
int postion = duelist.get(i).getPayment_id().getId();
if (postion == pos + 1) {
arrayDueDetail.add(duelist.get(i));
}
}
paymentlist = Entity.query(Payment.class).executeMulti();
for (int i = 0; i < paymentlist.size(); i++) {
arrayPayment.add(paymentlist.get(i));
}
// for calculating the total of collected due in the duedetail
// fragment
for (int i = 0; i < arrayDueDetail.size(); i++) {
if (arrayDueDetail.get(i).getAmount() != null) {
int dueAmount = Integer.parseInt(arrayDueDetail.get(i)
.getAmount());
total += dueAmount;
}
}
//
}
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.due_amounts_duedetails_history,
container, false);
this.view = view;
dueActivity = (Due) getActivity();
position = dueActivity.getIndex();
DecimalFormat formatter = new DecimalFormat("#,###,###");
totalInitialDue = (TextView) view.findViewById(R.id.tvRemainingDue);
totalInitialDue.setText("BDT "
+ arrayPayment.get(position).getInitialDue());
TotalCollectedDue = (TextView) view
.findViewById(R.id.tvTotalCollectedDueAmount);
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT " + totalduecollection);
updateUI();
return view;
}
View view;
public void updateUI() {
if (view == null)
return;
collectionbtn = (TextView) view.findViewById(R.id.btnCollection);
collectionbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(getActivity());
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.due_collection_popup);
// d.requestWindowFeature(Window.FEATURE_NO_TITLE);
final EditText et = (EditText) d
.findViewById(R.id.etduecollectionamount);
d.findViewById(R.id.btnCollectionOk).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
dueAmmount = et.getText().toString();
if (dueAmmount != null) {
if (!(dueAmmount.equals(""))) {
int incremental_position = position + 1;
// creating a object of duecollection
odi = new DueCollection();
odi.setAmount(dueAmmount);
SimpleDateFormat sdf = new SimpleDateFormat(
"dd MMMM,yyyy");
String currentDate = sdf
.format(new Date());
odi.setDate(currentDate);
Payment payObj = Entity
.query(Payment.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setPayment_id(payObj);
om = Entity
.query(OrderModel.class)
.where("_id='"
+ incremental_position
+ "'").execute();
odi.setOrder_id(om);
odi.save();
arrayDueDetail.add(odi);
// *** duecollection obj creation ends
// here
total = 0;
dueDetailAdapter.notifyDataSetChanged();
for (int i = 0; i < arrayDueDetail
.size(); i++) {
double dueAmount = Integer
.parseInt(arrayDueDetail
.get(i).getAmount());
total += dueAmount;
}
String DueOnOrder = arrayPayment.get(
position).getInitialDue();
double remainingdue = Double
.parseDouble(DueOnOrder)
- total;
dueActivity.dueArray.get(position)
.setAmount(remainingdue);
dueActivity.dueadapter
.notifyDataSetChanged();
payObj.setAmount(remainingdue);
payObj.setSynced("0");
payObj.save();
// set the total remaining due to the
// header textview
String totalduecollection = amountFormatter(total);
TotalCollectedDue.setText("BDT "
+ totalduecollection);
dueActivity.stateStore = "" + position;
setClicked = true;
}
}
d.dismiss();
}
});
d.show();
d.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// dueActivity.populateArray();
Formater fobJ = new Formater();
DueCollectionAsyncTask dcat = new DueCollectionAsyncTask(
dueActivity, "" + odi.getOrder_id().getId(), ""
+ odi.getPayment_id().getOutlet_id()
.getId(), dueAmmount, fobJ
.getDateinPrefferedFormat());
dcat.execute();
}
});
}
});
// dueActivity.header.performClick();
dueDetailList = (ListView) view.findViewById(R.id.listViewDueDetails);
dueDetailAdapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
convertView = inflater.inflate(
R.layout.due_amounts_duedetails_product_items, null);
// }
TextView dueFragproduct = (TextView) convertView
.findViewById(R.id.tvduefragDate);
TextView dueFragDueCollectionAmmount = (TextView) convertView
.findViewById(R.id.tvduefragProductAmmount);
dueFragproduct.setText(arrayDueDetail.get(position).getDate());
DecimalFormat formatter = new DecimalFormat("#,###,###");
String commaformatedstring = ""
+ arrayDueDetail.get(position).getAmount();
dueFragDueCollectionAmmount.setText("BDT "
+ commaformatedstring);
return convertView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayDueDetail.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayDueDetail.size();
}
};
dueDetailList.setAdapter(dueDetailAdapter);
dueDetailList.setDivider(null);
dueDetailList.setDividerHeight(0);
setListViewHeightBasedOnChildren(dueDetailList);
}
/****
* Method for Setting the Height of the ListView dynamically. Hack to fix
* the issue of not showing all the items of the ListView when placed inside
* a ScrollView
****/
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
public void confirmationDialog(String msg, String title, final Dialog d) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setMessage(msg);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
d.dismiss();
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
AlertDialog alertDialog2 = alertDialogBuilder.create();
alertDialog2.show();
Button nbutton = alertDialog2
.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setBackgroundColor(Color.parseColor("#47b96b"));
Button pbutton = alertDialog2
.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(Color.parseColor("#e06165"));
int textViewId = alertDialog2.getContext().getResources()
.getIdentifier("android:id/alertTitle", null, null);
TextView tv = (TextView) alertDialog2.findViewById(textViewId);
tv.setTextColor(getResources().getColor(R.color.coral_blue));
}
public String amountFormatter(double number) {
DecimalFormat formatter = new DecimalFormat("#,###,###");
String totalduecollection = formatter.format(Double.parseDouble(""
+ number));
return totalduecollection;
}
}
The button displays a dialog through which ListView inside the fragment gets populated.
not exactly clear to me. Did you meant inside your dialog you have some action that reflects on the fragment lisview?
have to click the parent list view item again to see the fragment and its content. I want the Fragment view and its updated content remain viewed after the dialog is dismissed
What i understand here u are doing something inside child view fragment that reflects on parent view list item, you are expecting the parent item data to be updated in view and also keeping the view state here u meant to be opened the parent item as it was (when u are updating the something inside fragment or dialog whatever)
My primary answer is you keep somehow keep the position to a member reference of the activity class where you actually setting the parent list in parent item onClick callback.
keep this position and later what you have to is to call a method inside adapter to pass the position to set a perform clic on item view
you may get a hints from this link..
http://blog.wittchen.biz.pl/how-to-highlight-and-click-on-listview-item-in-android-programmatically/