2016-01-29 1 views
0

Хорошие парни дня, Я успешно заполнил свой собственный-listview-layout в своей деятельности, , но проблема в том, что я не могу получить все значение заполненного EditText в моем списке , пожалуйста, помогите мне, что подход, который я должен делать, благодаряКак получить всю ценность EditText в Custom ListView

enter image description here

Picture Adapter.java

public View getView(int position, View convertView, ViewGroup parent) { 
    View row; 
    row = convertView; 
    final dataHandler handler; 
    if(convertView == null){ 
     LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     row = inflater.inflate(R.layout.row_layout,parent, false); 
     handler = new dataHandler(); 
     handler.pictures = (ImageView) row.findViewById(R.id.pictures); 
     handler.name = (TextView) row.findViewById(R.id.picturename); 
     handler.price= (EditText) row.findViewById(R.id.price); 
     handler.add = (Button) row.findViewById(R.id.btnplus); 
     handler.minus = (Button) row.findViewById(R.id.btnminus); 
     row.setTag(handler); 
    }else{ 
     handler = (dataHandler) row.getTag(); 
    } 
    PSP psp; 
    psp =(PSP) this.getItem(position); 
    Picasso.with(getContext()).load(psp.getPicture()).resize(200, 155).into(handler.pictures); 
    handler.name.setText(psp.getName()); 
    handler.price.setText(psp.getPrice()); 
return row; 
} 

MainActivity.java

PictureAdapter adapter; 
listView = (ListView) findViewById(R.id.ls); 
adapter = new PictureAdapter(this,R.layout.row_layout); 
listView.setAdapter(adapter); 
try { 
    JSONArray users = response.getJSONArray("user"); 
    for (int x = 0; x <= users.length()-1; x++) { 
     JSONObject user = users.getJSONObject(x); 
     PSP psp = new PSP(imageUri+user.getString("image")+".png",user.getString("username"),"0"); 
     adapter.add(psp); 
    } 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 

PSP.java

public class PSP 

{

private String picture; 
private String name; 
private String price; 

public String getPicture() { 
    return picture; 
} 

public PSP(String picture, String name, String price){ 
    this.setPicture(picture); 
    this.setName(name); 
    this.setPrice(price); 
} 

public void setPicture(String picture) { 
    this.picture = picture; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getPrice() { 
    return price; 
} 

public void setPrice(String price) { 
    this.price = price; 
} 

}

row_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" android:layout_height="80dp" 
android:background="#000000"> 

<ImageView 
    android:id="@+id/pictures" 
    android:layout_width="100dp" 
    android:layout_height="75dp" 
    android:layout_alignParentLeft="true" 

    /> 
<TextView 
    android:id="@+id/picturename" 
    android:layout_width="115dp" 
    android:layout_height="75dp" 
    android:layout_toRightOf="@+id/pictures" 
    android:text="Kim Domingo" 
    android:gravity="center" 
    android:textColor="#FFFFFF" 
    /> 
<Button 
    android:id="@+id/btnplus" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:gravity="center" 
    android:text="+" 
    android:textSize="50px" 
    android:layout_centerVertical="true" 
    android:layout_toRightOf="@+id/picturename" 
    android:layout_toEndOf="@+id/picturename" 
    /> 


<EditText 
    android:id="@+id/price" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:focusable="false" 
    android:textColor="#FFFFFF" 
    android:inputType="number" 
    android:gravity="center" 
    android:layout_centerVertical="true" 
    android:layout_toRightOf="@+id/btnplus" 
    android:layout_toEndOf="@+id/btnplus" /> 

<Button 
    android:id="@+id/btnminus" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:gravity="center" 
    android:text="-" 
    android:textSize="50px" 
    android:layout_centerVertical="true" 
    android:layout_toRightOf="@+id/price" 
    android:layout_toEndOf="@+id/price" /> 

<View 
    android:layout_width="match_parent" 
    android:layout_height="2dp" 
    android:background="#FFFFFF" 
    android:layout_below="@+id/pictures" 
    android:id="@+id/editText"></View> 

+0

А где код, который вы получите значение из ListView, что ответ или ошибка, которую вы получаете? –

+0

Я не знаю, какой подход мне следует сделать, я новичок :) – zxcetera

+0

Просто добавьте поле «число» в вашем классе PSP, чтобы сохранить значение каждого EditText. – CrazyOrr

ответ

2

я создал же перед тем, как этот

enter image description here

Вы можете использовать HashMap карту = новый HashMap <>(); для чего пользователь нажимает. Я предполагаю, что вы используете два нажатия кнопки доступны в классе адаптера, если не добавить его.

Шаг 1 Первый Объявляет HashMap карту = новый HashMap <>(); в адаптер.

Шаг 2 Затем поместите значение в HashMap map.put («ключ», «значение»); Этот код помещается как в событие плюс, так и минус.

Этап 3 Звонок ShowHashMapValue(); ниже к map.put («ключ», «значение»); для просмотра значений HashMap для проверки logcat.

Сравните этот код адаптера, чтобы легко понять, если какая-либо проблема, просто комментарий ниже.

ListAdapter.java

public class ListAdapter extends BaseAdapter { 

    public ArrayList<Integer> quantity = new ArrayList<Integer>(); 
    public ArrayList<Integer> price = new ArrayList<Integer>(); 
    private String[] listViewItems, prices, static_price; 
    TypedArray images; 
    View row = null; 

    static String get_price, get_quntity; 
    int g_quntity, g_price, g_minus; 

    private Context context; 
    CustomButtonListener customButtonListener; 

    static HashMap<String, String> map = new HashMap<>(); 


    public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) { 
     this.context = context; 
     this.listViewItems = listViewItems; 
     this.images = images; 
     this.prices = prices; 

     for (int i = 0; i < listViewItems.length; i++) { 
      quantity.add(0); 
     } 
    } 

    public void setCustomButtonListener(CustomButtonListener customButtonListner) { 
     this.customButtonListener = customButtonListner; 
    } 

    @Override 
    public int getCount() { 
     return listViewItems.length; 
    } 

    @Override 
    public String getItem(int position) { 
     return listViewItems[position]; 
    } 


    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 

     final ListViewHolder listViewHolder; 
     if (convertView == null) { 
      LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false); 
      listViewHolder = new ListViewHolder(); 
      listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName); 
      listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct); 
      listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice); 
      listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew); 
      listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity); 
      listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove); 
      static_price = context.getResources().getStringArray(R.array.Price); 
      row.setTag(listViewHolder); 
     } else { 
      row = convertView; 
      listViewHolder = (ListViewHolder) convertView.getTag(); 
     } 

     listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1)); 
     listViewHolder.edTextQuantity.setText(quantity.get(position) + ""); 
     listViewHolder.tvProductName.setText(listViewItems[position]); 
     listViewHolder.tvPrices.setText(prices[position]); 


     listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       if (customButtonListener != null) { 
        customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1); 

        quantity.set(position, quantity.get(position) + 1); 
        //price.set(position, price.get(position) + 1); 

        row.getTag(position); 

        get_price = listViewHolder.tvPrices.getText().toString(); 

        g_price = Integer.valueOf(static_price[position]); 

        get_quntity = listViewHolder.edTextQuantity.getText().toString(); 
        g_quntity = Integer.valueOf(get_quntity); 

        map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString()); 
//     Log.d("A ", "" + a); 
//     Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show(); 
//     Log.d("Position ", "" + position); 
//     System.out.println(+position + " Values " + map.values()); 
        listViewHolder.tvPrices.getTag(); 
        listViewHolder.tvPrices.setText("" + g_price * g_quntity); 
        ShowHashMapValue(); 

       } 


      } 

     }); 
     listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       if (customButtonListener != null) { 

        customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1); 
        if (quantity.get(position) > 0) 
         quantity.set(position, quantity.get(position) - 1); 

        get_price = listViewHolder.tvPrices.getText().toString(); 
        g_minus = Integer.valueOf(get_price); 
        g_price = Integer.valueOf(static_price[position]); 
        int minus = g_minus - g_price; 
        if (minus >= g_price) { 
         listViewHolder.tvPrices.setText("" + minus); 
        } 
        map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString()); 
        ShowHashMapValue(); 
       } 
      } 
     }); 


     return row; 
    } 

    private void ShowHashMapValue() { 
     /** 
     * get the Set Of keys from HashMap 
     */ 
     Set setOfKeys = map.keySet(); 

/** 
* get the Iterator instance from Set 
*/ 
     Iterator iterator = setOfKeys.iterator(); 

/** 
* Loop the iterator until we reach the last element of the HashMap 
*/ 
     while (iterator.hasNext()) { 
/** 
* next() method returns the next key from Iterator instance. 
* return type of next() method is Object so we need to do DownCasting to String 
*/ 
      String key = (String) iterator.next(); 

/** 
* once we know the 'key', we can get the value from the HashMap 
* by calling get() method 
*/ 
      String value = map.get(key); 

      System.out.println("Key: " + key + ", Value: " + value); 
     } 
    } 
} 
+0

спасибо, я попробую это :) – zxcetera

+0

Работаю правильно, спасибо за отличный образец кода :) – zxcetera

+1

ваш прием в любое время –

0

Итак, вот логика. Вы должны объявить логическое значение в PSP. по умолчанию установите его на false.

Теперь, когда + кнопка будет срабатывать вам необходимо установить, что логическое check к true

то в вашей установленной цене создать эту логику.

public String getPrice() { 

    if(check==true){ 
     price++; 
    } 
    else{ 
    price--; 
    } 
    return price; 
} 

Если я правильно вас понимаю, это, безусловно, поможет вам. Удачи!

+0

Я сейчас все равно спасибо :), – zxcetera

Смежные вопросы