RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 785139
Accepted
R1zen
R1zen
Asked:2020-02-14 21:44:05 +0000 UTC2020-02-14 21:44:05 +0000 UTC 2020-02-14 21:44:05 +0000 UTC

游标加载器。预处理数据库中的数据

  • 772

下午好。实现了一种商店。有一个包含ImageView两个TextView. View来自数据库的数据使用CursorLoader. 单击View产品时,数据库中的字段会更新,这表明该产品已被购买(零或一)。到目前为止,一切都运行良好。以及如何在加载商店时处理数据?有必要这样做:如果产品在数据库中有一个单元,那么它是View不可点击的。

public class ShopActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>{
    SimpleCursorAdapter scAdapter;
    ListView lvData;
    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop2);
        dbHelper = new DBHelper(this);

        String[] from = new String[] { DBHelper.ITEMS_IMAGE, DBHelper.ITEMS_NAME, DBHelper.ITEMS_COST };
        int[] to = new int[] { R.id.radioImageIV, R.id.radioDescriptionTV, R.id.radioCostTV}; 

        scAdapter = new SimpleCursorAdapter(this, R.layout.shop_item_radio, null, from, to, 0);

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

        lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setClickable(false);

                new ProgramManager(Shop2Activity.this).setBought(view); //обновляет запись в БД
            }
        });

        lvData.setAdapter(scAdapter); 
        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
        return new MyCursorLoader(this, dbHelper);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        scAdapter.swapCursor(cursor);
    }

   static class MyCursorLoader extends CursorLoader {
        DBHelper dbHelper;

        public MyCursorLoader(Context context, DBHelper db) {
            super(context);
            this.dbHelper = db;
        }

        @Override
        public Cursor loadInBackground() {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            Cursor cursor = db.query(DBHelper.ITEMS_TABLE_NAME, null, null, null, null, null,null);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return cursor;
        }

    }

shop_item_radio.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:background="@drawable/border_shop"
    android:fillViewport="true"
    android:isScrollContainer="true">

    <ImageView
        android:id="@+id/radioImageIV"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/border"
        android:padding="4dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/radio" />

    <TextView
        android:id="@+id/radioDescriptionTV"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="8dp"
        android:textAlignment="textStart"
        android:textColor="#004D40"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/radioImageIV"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/radioCostTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:drawableLeft="@drawable/ic_money_24dp"
        android:text="10000"
        android:textAlignment="gravity"
        android:textColor="#004D40"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/radioDescriptionTV" />
</android.support.constraint.ConstraintLayout>
android
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    pavlofff
    2020-02-14T23:09:19Z2020-02-14T23:09:19Z

    大概就是这样一个适配器,我没有机会去测试,大家理解,但是思路应该很清楚:

    public class ShopAdapter extends SimpleCursorAdapter {
    
            private Context mContext;
            private int layout;
            private Cursor cr;
            private final LayoutInflater inflater;
    
            public ShopAdapter(Context context, int layout, Cursor c, String[] from,int[] to, int flag) {
                super(context, layout, c, from, to, flag);
                this.layout=layout;
                this.mContext = context;
                this.inflater=LayoutInflater.from(context);
                this.cr=c;
            }
    
            @Override
            public View newView (Context context, Cursor cursor, ViewGroup parent) {
                    return inflater.inflate(layout, null);
            }
    
            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                super.bindView(view, context, cursor);
    
                ConstraintLayout item =(ConstraintLayout)view.findViewById(R.id.item);
                // здесь вместо  "isBought" можно вставить константу из контракта, типа DBHelper.IS_BOUGHT
                int column=cursor.getColumnIndexOrThrow("isBought");  
    
                item.setEnabled(cursor.getInt(column) != 1); // кликабельно если содержимое колонки не = 1
            }
    
    }
    

    在项目的标记中,必须为根布局分配一个 ID:

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
    
        android:id = "@+id/item"
    
        ...     >
    
    
    </android.support.constraint.ConstraintLayout>
    

    在活动中,我们使用我们的适配器而不是标准适配器:

    String[] from = new String[] { DBHelper.ITEMS_IMAGE, DBHelper.ITEMS_NAME, DBHelper.ITEMS_COST };
    int[] to = new int[] { R.id.radioImageIV, R.id.radioDescriptionTV, R.id.radioCostTV}; 
    
    scAdapter = new ShopAdapter(this, R.layout.shop_item_radio, null, from, to, 0);
    
    • 2
  2. R1zen
    2020-02-15T15:13:50Z2020-02-15T15:13:50Z

    我将把适配器的工作版本留在这里,也许有人会派上用场。谢谢@pavlofff ShopAdapter.java

    public class ShopAdapter extends SimpleCursorAdapter implements View.OnClickListener{
    
            private Context mContext;
            private int layout;
            private Cursor cr;
            private final LayoutInflater inflater;
    
    
            public ShopAdapter(Context context, int layout, Cursor c, String[] from,int[] to, int flag) {
                super(context, layout, c, from, to, flag);
                this.layout=layout;
                this.mContext = context;
                this.inflater=LayoutInflater.from(context);
                this.cr = c;
            }
    
            @Override
            public View newView (Context context, Cursor cursor, ViewGroup parent) {
                    return inflater.inflate(layout, null);
            }
    
            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                super.bindView(view, context, cursor);
    
                ConstraintLayout item = view.findViewById(R.id.item);
                item.setOnClickListener(this);
                TextView cost = view.findViewById(R.id.radioCostTV);
                int img = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.ITEMS_COST_ICON));
                int column = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.ITEMS_IS_BOUGHT));
                if (column == 1){
                    view.setClickable(false); // кликабельно если содержимое колонки не = 1
                    cost.setText("Куплено");
                    //если раскоментить строку ниже, начинает работать странно. При покупке любого предмета, иконка меняется и у первого (при этом он кликабелен). `Пришлось тянуть иконки из БД.
                    //cost.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
                }
                cost.setCompoundDrawablesWithIntrinsicBounds(img, 0, 0, 0);
            }   
                else {
                    view.setClickable(true);
                    //cost.setText("НЕ куплено");
                }
        @Override
        public void onClick(View v) {
                //обработчик кликов пришлось делать в адаптере
            TextView cost = v.findViewById(R.id.radioCostTV);
            if (GameActivity.hero.getMoney() >= Integer.parseInt(cost.getText().toString())) {
                new ProgramManager(mContext).setBought(v);
    
                cost.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
                cost.setText("Куплено");
                v.setClickable(false);
            }
            else
                Toast.makeText(mContext, "no money", Toast.LENGTH_SHORT).show();
        }
    }
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5