android - 单击时将项目移动到 ListView 的底部

标签 android listview onitemclicklistener

我很难搞清楚这个问题,我需要能够单击 ListView 的一个项目,然后将该项目移动到列表的底部,并更改一些背景颜色以产生差异,然后如果单击返回,则将其返回到列表中的原始位置。

我试过 list.addFooterView() 但我不能让它那样工作,它只是将一个空项目附加到页脚,我无法让它回到原来的位置。

到目前为止,这是我的代码。任何有关如何解决此问题的想法都将受到赞赏。

ActivityProductsBuy.java

package com.roneskinder;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.roneskinder.model.DataProducts;
import com.roneskinder.utils.DatabaseHandler;
import com.roneskinder.x111.R;

public class ActivityProductsBuy extends Activity {

    protected Context mContext;

    protected DatabaseHandler db;
    private SQLiteDatabase newDB;
    private String tableProducts = DatabaseHandler.TABLE_PRODUCTS;

    protected ListView lvProducts;
    protected String title, idProduct, idGroceryList, ProductCode, ProductName;
    protected int totalItems, itemsInCart = 0;
    protected Button btn_itemsInCart;
    protected TextView tv_percentText;

    /** The data used for products */
    private List<DataProducts> info;

    /** The Adapter holds the listview. */
    private ProductsItemAdapter adapter1;

    private static final int ZBAR_SCANNER_REQUEST = 0;

    protected SharedPreferences preferences;

    protected String TAG = ActivityProductsBuy.class.getName();

    ImageView imgHolder;
    Paint paint;
    EditText edtPercentage;

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

        mContext = getApplicationContext();

        // Get Database values for User
        db = new DatabaseHandler(mContext);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        // remove and add products to DB
        //db.removeAllProducts();
        // this.addProducts();

        // get intent Extras (the title, list id)
        //title = getIntent().getExtras().getString("title");
        idGroceryList = getIntent().getExtras().getString("idGroceryList");

        lvProducts = (ListView) findViewById(R.id.lvProducts);

        info = new ArrayList<DataProducts>();
        imgHolder = (ImageView) findViewById(R.id.coringImage);
        btn_itemsInCart = (Button) findViewById(R.id.btn_itemsInCart);
        tv_percentText = (TextView) findViewById(R.id.percentText);
        tv_percentText.setText("0%");

        paint = new Paint();

        adapter1 = new ProductsItemAdapter(this, info);

        // load all database products into listview
        lvProducts.setAdapter(adapter1);
        loadProducts();
        totalItems = adapter1.getCount();

        lvProducts.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                itemsInCart++;
                if(itemsInCart <= totalItems){
                    btn_itemsInCart.setText("(" + itemsInCart + "/"+ totalItems +")");
                    // Fill percentage of image
                    float percentage = ((float)itemsInCart/(float)totalItems)*100;
                    Log.d(TAG, "percentage: " + percentage);
                    imgHolder.setImageResource(R.drawable.cart_default);

                    if (percentage > 0 && percentage <= 100) {
                        imgHolder.setImageBitmap(doBottomToTopOperation(Math.round(percentage)));
                        tv_percentText.setText((int)percentage + "%");
                    }
                }
            }
        });
    }

    public void loadProducts() {
        info.clear();
        ((BaseAdapter) lvProducts.getAdapter()).notifyDataSetChanged();
        Cursor cur = null;
        try {
            newDB = db.getWritableDatabase();
            cur = newDB.rawQuery(
                    "SELECT idProduct, ProductCode, name FROM "
                            + tableProducts + " WHERE idGroceryList = " + idGroceryList, null);

            Log.d(TAG, DatabaseUtils.dumpCursorToString(cur));

            if (cur != null) {
                // tvNoProducts.setVisibility(View.GONE);
                if (cur.moveToFirst()) {
                    do {
                        idProduct = cur.getString(cur.getColumnIndex("idProduct"));
                        ProductCode = cur.getString(cur.getColumnIndex("ProductCode"));
                        ProductName = cur.getString(cur.getColumnIndex("name"));

                        info.add(new DataProducts(ProductName, ProductCode,idProduct, "Vegetales", "0", idGroceryList));
                    } while (cur.moveToNext());
                }
            } else {
                // tvNoProducts.setVisibility(View.VISIBLE);
            }
        } catch (SQLiteException se) {
            Log.e(getClass().getSimpleName(),
                    "Could not create or Open the database");
        }

    }

    /**
     * The Class ProductsItemAdapter.
     */
    private class ProductsItemAdapter extends BaseAdapter {

        /** The context. */
        private Context context;

        /** The list. */
        private List<DataProducts> list;

        /** The inflater. */
        private LayoutInflater inflater;

        /**
         * Instantiates a new deal item adapter.
         * 
         * @param context
         *            the context
         * @param list
         *            the list
         */
        public ProductsItemAdapter(Context context, List<DataProducts> list) {
            this.context = context;
            this.list = list;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.adapter_products, null);
            }
            TextView txt1 = (TextView) convertView
                    .findViewById(R.id.tvProductName);
            TextView txt2 = (TextView) convertView
                    .findViewById(R.id.tvProductCode);
            TextView tv1 = (TextView) convertView
                    .findViewById(R.id.tvProductPrice);
            TextView tv2 = (TextView) convertView
                    .findViewById(R.id.tvProductCategory);

            final DataProducts dInfo = list.get(position);
            txt1.setText(dInfo.getProductName());
            txt2.setText(dInfo.getProductCode());

            tv1.setText(dInfo.getProductPrice());
            // tv1.setPaintFlags(tv1.getPaintFlags() |
            // Paint.STRIKE_THRU_TEXT_FLAG);

            tv2.setText(dInfo.getProductCategory());
            return convertView;
        }

    }

    public Bitmap doBottomToTopOperation(int percentage) {
        Bitmap bitmapOriginal = ((BitmapDrawable) imgHolder.getDrawable()).getBitmap();

        Bitmap bitmapTarget = BitmapFactory.decodeResource(getResources(), R.drawable.cart_filled);

        int heightToCrop = bitmapTarget.getHeight() * (100 - percentage) / 100;

        Bitmap croppedBitmap = Bitmap.createBitmap(bitmapTarget, 0, heightToCrop, bitmapTarget.getWidth(), bitmapTarget.getHeight() - heightToCrop);

        Bitmap bmOverlay = Bitmap.createBitmap(bitmapOriginal.getWidth(),
                bitmapOriginal.getHeight(), bitmapOriginal.getConfig());
        Canvas canvas = new Canvas(bmOverlay);
        canvas.drawBitmap(bitmapOriginal, new Matrix(), null);
        canvas.drawBitmap(croppedBitmap,
                canvas.getWidth() - croppedBitmap.getWidth(),
                canvas.getHeight() - croppedBitmap.getHeight(), null);

        return bmOverlay;
    }

}

activity_products_buy.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.sothree.slidinguppanel.SlidingUpPanelLayout
        xmlns:sothree="http://schemas.android.com/apk/res-auto"
        android:id="@+id/sliding_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        sothree:umanoPanelHeight="68dp"
        sothree:umanoShadowHeight="4dp" >

        <!-- MAIN LAYOUT -->

        <ListView
            android:id="@+id/lvProducts"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/myFilter" >
        </ListView>

        <!-- SLIDING LAYOUT -->

        <LinearLayout
            android:id="@+id/dragView"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:background="#ffffff"
            android:clickable="true"
            android:focusable="false"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="68dp"
                android:background="#f0f0f0"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/name"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:gravity="center_vertical"
                    android:paddingLeft="10dp"
                    android:text="Total de Productos en el carrito"
                    android:textColor="#000"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/btn_itemsInCart"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:gravity="center_vertical|right"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp"
                    android:text="(0)"
                    android:textColor="#000"
                    android:textSize="14sp" />
            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/coringImage"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:src="@drawable/cart_default" />

                <TextView
                    android:id="@+id/percentText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/coringImage"
                    android:layout_alignLeft="@+id/coringImage"
                    android:layout_alignRight="@+id/coringImage"
                    android:layout_alignTop="@+id/coringImage"
                    android:layout_margin="1dp"
                    android:gravity="center"
                    android:text="0%"
                    android:textColor="#ffffff" />
            </RelativeLayout>
        </LinearLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>

</RelativeLayout>

适配器_产品.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="@dimen/pad_10dp"
    android:paddingRight="@dimen/pad_10dp"
    android:paddingTop="@dimen/pad_15dp" >

    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/item_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/pad_10dp"
            android:src="@drawable/icon_mypurchase1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="@dimen/pad_10dp" >

        <LinearLayout
            android:id="@+id/right_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tvProductName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Nombre del Producto" />

                <TextView
                    android:id="@+id/tvProductCode"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="@dimen/pad_2.5dp"
                    android:text="Codigo" />
            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tvProductPrice"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/$45"
                    android:textColor="@color/red_main"
                    android:textSize="@dimen/txt_18sp" />

                <TextView
                    android:id="@+id/tvProductCategory"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Categoria"
                    android:textSize="@dimen/txt_12sp" />
            </LinearLayout>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="@dimen/pad_15dp"
            android:background="@color/my_purchase_list_sap" />
    </LinearLayout>

</LinearLayout>

最佳答案

只需更改数据源中项目的索引,然后 notifyDataSetChanged()

DataProducts item = info.get(<index>);
info.remove(<index>);
info.add(item);
adapter1.notifyDataSetChanged();

getView中为底部项目设置背景,

if (position==getCount()-1){
    convertView.setBackground(<backgroud>);
}

如果你想把它移回去,

DataProducts item = info.get(info.size()-1);
info.remove(info.size()-1);
info.add(<original_index>,item);
adapter1.notifyDataSetChanged();

关于android - 单击时将项目移动到 ListView 的底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553346/

相关文章:

android listview 问题,覆盖 getView() 但它永远不会被调用

python - 如何更改 ttk.Combobox ListView 中的背景颜色?

android - 如何使用 SimpleCursorAdapter 使用 android.R.id.list 设置 onItemClickListener

android - 如何获取在 Play 商店写反馈的客户的电子邮件 ID

android - 在哪里存储密码?

android - 如何为最终用户调试 Android 应用卡住但不崩溃

android - 我应该在 Firestore 的字段文档中只写标识符还是写所有数据?

WPF 和 ListView 。 Shift - 选择多个项目。错误的开始项目

java - fragment 中的 onItemClicked()

android - 实现 OnItemClickListener,但 onItemClick 不起作用