android listview 每行的金额 求总和
PHP中文网
PHP中文网 2017-04-17 17:49:42
0
4
444

我用listview 把一些数据通过simpleAdapter 展示出来。 详情如截图

加减 按钮是修改数量。 与此同时,右边的 和 也会随着数量的更改而 更新。

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 - listview和底部的总和 textview分开

<?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 值 加起来 ,然后再底部展示出总和? 我知道大概是用循环,但是实际操作完全没有头绪。
请大神们指点**

PHP中文网
PHP中文网

认证高级PHP讲师

모든 응답(4)
黄舟

@mw2972님의 답변에 추가하겠습니다.
총 가격은 초기 데이터와 각 작업에만 관련되므로 Activity에 총 가격 변수 totalPrice를 유지한 후 초기화할 때 제공하면 됩니다. 목록 값이 할당되어 있으며 더하기 또는 빼기 작업을 클릭할 때마다 값을 수정하여 현재 목록의 총 가격을 항상 알 수 있습니다.

초기화 시점: 목록 데이터를 어댑터에 할당할 때 데이터를 한 번 순회하면 총 가격이 계산됩니다.
수정 시점: 덧셈, 뺄셈 연산을 클릭할 때 수정하고 총 가격을 업데이트합니다. 동시에 TextView 콘텐츠를 표시하면 됩니다.

결국 AdapterActivity을 넣는 것은 사실 나쁜 습관입니다.

左手右手慢动作

eventBus 또는 RxBus 사용

左手右手慢动作

데이터를 분리하여 표시하는 것이 가장 좋으며 인터페이스의 텍스트를 데이터 소스로 의존하지 마십시오.
더하기 또는 빼기 버튼 클릭을 포함하여 수량 배열의 값을 수정한 다음 인터페이스를 업데이트해야 합니다

합계는 각 행의 가격 x 수량을 더한 후 아래 텍스트를 업데이트하세요

洪涛

먼저 수량, 가격, 이름의 세 가지 배열을 활동 멤버 변수로 변경하여 다양한 뷰에서 액세스할 수 있도록 합니다.
그런 다음 각 onClick 메서드를 수정합니다. 이제 모든 품목의 수량과 단가에 접근할 수 있으므로 총 가격을 계산하는 것이 어렵지 않습니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!