2016-10-20 3 views
1

У меня есть 3 массива для имени, количества и цены.Android listview simpleAdapter получает сумму каждого последнего столбца Row Textview

Я использую Listview для отображения их с помощью SimpleAdapter. Кроме того, у меня есть две кнопки в каждом ряду, которые используются для управления количеством - плюс и минусом.

При нажатии кнопки «Плюс» или «Минус» количество будет изменяться, и итоговое значение этой строки также будет обновлено.

Если количество = 1, при нажатии на кнопку «минус» оно останется 1;

пока все функции работают правильно.

enter image description here

Java

int cal_quantity; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main8); 

List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>(); 

final String name[]={"apple","orange","pear"}; 
final String quantity[]={"1","2","3"}; 
final String price[]={"5","10","2"}; 

for(int i=0;i<name.length;i++){ 
    HashMap<String, String> map = new HashMap<>(); 
    map.put("name",name[i]); 
    map.put("quantity",quantity[i]); 
    map.put("price",price[i]); 
    aList.add(map); 
} 

String[] from = {"name","quantity","price"}; 
int[] to = {R.id.name,R.id.quantity,R.id.price}; 

SimpleAdapter adapter = new SimpleAdapter(this, aList, R.layout.main7, from, to){ 
    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 

     View v = super.getView(position, convertView, parent); 
     final TextView tv_quantity=(TextView)v.findViewById(R.id.quantity); 
     final TextView tv_price=(TextView)v.findViewById(R.id.price); 
     final TextView tv_total=(TextView)v.findViewById(R.id.total); 

     final int get_quantity = Integer.parseInt(tv_quantity.getText().toString()); 
     final double get_price= Double.parseDouble(tv_price.getText().toString()); 
     final double get_total=get_quantity*get_price; 
     tv_total.setText(get_total+""); 

     Button minus=(Button)v.findViewById(R.id.minus); 
     minus.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       cal_quantity=Integer.parseInt(tv_quantity.getText().toString()); 
       if(cal_quantity!=1){ 
        cal_quantity=cal_quantity-1; 
       } 
       tv_quantity.setText(cal_quantity+""); 
       double get_total=cal_quantity*get_price; 
       tv_total.setText(get_total+""); 
      } 
     }); 

     Button plus=(Button)v.findViewById(R.id.plus); 
     plus.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       cal_quantity=Integer.parseInt(tv_quantity.getText().toString()); 
       cal_quantity=cal_quantity+1; 
       tv_quantity.setText(cal_quantity+""); 
       double get_total=cal_quantity*get_price; 
       tv_total.setText(get_total+""); 
      } 
     }); 
     return v; 
    } 
}; 

ListView listView = (ListView) findViewById(R.id.listview); 
listView.setAdapter(adapter); 

} 

XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/activity_main8" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.yu.singleton.Main8Activity" 
android:orientation="vertical"> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_weight="0.3" 
    android:layout_height="match_parent"> 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/listview" /> 
</LinearLayout> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:background="@android:color/holo_blue_dark" 
    android:layout_weight="0.7" 
    android:layout_height="match_parent"> 

    <TextView 
     android:text="Total" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView3" 
     android:textAlignment="center" 
     android:textSize="36sp" /> 
</LinearLayout> 
</LinearLayout> 

Мой вопрос заключается в том, чтобы добавить в Подитог каждой строки, а затем отобразить его в TextView (Всего) под списком

ответ

1

Вы должны сохранять количество в источнике данных каждый раз, когда вы плюс или минус.
Вот способ, чтобы сохранить количество к источнику данных и рассчитать общие при минус, вы должны сделать то же самое для плюса

minus.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     cal_quantity = Integer.parseInt(tv_quantity.getText().toString()); 
     if (cal_quantity != 1) { 
      cal_quantity = cal_quantity - 1; 
     } 

     // Save the quantity to your datasource (aList) 
     aList.get(position).put("quantity", "" + cal_quantity); 

     // Calculate total 
     int total = 0; 
     Log.d("TAG", "start total = " +total); 
     for (int i = 0; i < aList.size(); i++) { 
      Log.d("TAG", "at "+i+ " quantity = " +aList.get(i).get("quantity")); 
      total += Integer.parseInt(aList.get(i).get("quantity")) * Integer.parseInt(aList.get(i).get("price")); 
      Log.d("TAG", "at "+i+ " total = " +total); 
     } 
     // Display total, currently I use Toast, you can display it into your TextView 
     Toast.makeText(getApplicationContext(), "Total " + total, Toast.LENGTH_SHORT).show(); 

     ... 
    } 
}); 
+0

эй! thx для ответа ур. Однако математический расчет неверен. Он подходит только для первого нажатия кнопки. при нажатии 2-го или более раз, математический расчет неверен. любая идея, что не так? – gosulove

+0

@gosulove У меня есть 2 logcat к моему ответу, пожалуйста, помогите мне поместить его в ваш код, а затем запустите приложение еще раз и покажите мне, что показывает лог-код. спасибо –

+0

, пожалуйста, проверьте мой отредактированный вопрос. Я отправил туда вашу ссылку. thx – gosulove

1

То, что вы сейчас, как итоговому отражает суб общей сложности каждого элемента строки в ваш список.

Я бы рекомендовал переместить свой список hashmap в качестве переменной экземпляра для деятельности, чтобы иметь более широкую область действия, а также объявить другую переменную для хранения вашей общей суммы.

Напишите способ, который повторяет ваш список хэш-карт и для каждой итерации, получает количество, получает цену и умножает их вместе. Добавьте это значение в свою общую переменную на каждой итерации, и как только итератор завершится, установите значение полного текстового поля равным общей переменной. Установите, что общая переменная равна 0,0 в начале этого метода.

Вызовите этот метод в последней строке каждого из ваших слушателей. Я бы рекомендовал, чтобы вы сделали это объектно-ориентированным способом, в котором ваш список hashmap может быть просто простым списком объектов. Помогает с ясностью.

int cal_quantity; 
private int total; 
**private TextView grandTotal_TV;** 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main8); 
**grandTotal_TV = findViewById(R.id.TextView3);** 

List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>(); 

final String name[]={"apple","orange","pear"}; 
final String quantity[]={"1","2","3"}; 
final String price[]={"5","10","2"}; 

for(int i=0;i<name.length;i++){ 
    HashMap<String, String> map = new HashMap<>(); 
    map.put("name",name[i]); 
    map.put("quantity",quantity[i]); 
    map.put("price",price[i]); 
    aList.add(map); 
} 

String[] from = {"name","quantity","price"}; 
int[] to = {R.id.name,R.id.quantity,R.id.price}; 

SimpleAdapter adapter = new SimpleAdapter(this, aList, R.layout.main7, from, to){ 
    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 

     View v = super.getView(position, convertView, parent); 
     final TextView tv_quantity=(TextView)v.findViewById(R.id.quantity); 
     final TextView tv_price=(TextView)v.findViewById(R.id.price); 
     final TextView tv_total=(TextView)v.findViewById(R.id.total); 

     final int get_quantity = Integer.parseInt(tv_quantity.getText().toString()); 
     final double get_price= Double.parseDouble(tv_price.getText().toString()); 
     final double get_total=get_quantity*get_price; 
     tv_total.setText(get_total+""); 

     Button minus=(Button)v.findViewById(R.id.minus); 
     minus.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       cal_quantity=Integer.parseInt(tv_quantity.getText().toString()); 
       if(cal_quantity!=1){ 
        cal_quantity=cal_quantity-1; 
       } 
       tv_quantity.setText(cal_quantity+""); 
       double get_total=cal_quantity*get_price; 
       tv_total.setText(get_total+""); 
       **calculateTotal();** 
      } 
     }); 

     Button plus=(Button)v.findViewById(R.id.plus); 
     plus.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       cal_quantity=Integer.parseInt(tv_quantity.getText().toString()); 
       cal_quantity=cal_quantity+1; 
       tv_quantity.setText(cal_quantity+""); 
       double get_total=cal_quantity*get_price; 
       tv_total.setText(get_total+""); 
       **calculateTotal();** 
      } 
     }); 
     return v; 
    } 
}; 

ListView listView = (ListView) findViewById(R.id.listview); 
listView.setAdapter(adapter); 

} 
**private void calculateTotal() 
    { 
     total=0.0; 
     for(int i = 0; i<aList.size(); i++) 
     { 
      HashMap<String, String> map = aList.get(i); 
      int qty = Integer.parseInt(map.get("quantity")); 
      double price = Double.parseDouble(map.get("price")); 
      total+=qty*price; 

     } 
     grandTotal_TV.setText(total); 
    }** 
+0

Я попробую его позже и посмотрю, работает ли он. Кстати, вы пробовали это раньше? – gosulove

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