3

基本上,我是 Android 编程的菜鸟,除此之外,我还遇到了其他问题:我在主布局中声明了一个 GridView,并在单独的 xml 中定义了该网格的 XML 定义。我正在使用 SimpleCursorAdapter (不是自定义适配器)调整网格。问题是,当我触摸显示的数据行之一中的复选框时,我想记住相应 ROW_ID 的值......那么,是否有一个选项可以在不需要自定义 SimpleCursorAdapter 的情况下执行此操作(顺便说一句,是吗?可能的?)。

以下是 Layout XML 文件和代码的片段,我在其中使用 SimpleCursorAdapter 调整光标: main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BAF0ED"
    android:gravity="right" >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/view1"
        android:numColumns="2" >
    </GridView>

</RelativeLayout>

网格.xml:

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

    <TableRow>

        <TextView
            android:id="@+id/row_ID"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="5px"
            android:textColor="#4BA79E"
            android:textSize="22dp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="5px"
            android:textSize="22dp" />

        <TextView
            android:id="@+id/email"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="5px"
            android:textSize="22dp" />

        <CheckBox
            android:id="@+id/chk"
            android:layout_width="10px"
            android:layout_height="wrap_content"
            android:layout_weight="1" 
            android:onClick="x"/>
    </TableRow>

</TableLayout>

使用 SimpleCursorAdapter:

    public void showGridData() {
    @SuppressWarnings("static-access")
    String[] fromColumns = { db.KEY_ROWID, db.KEY_NAME, db.KEY_EMAIL };
    int[] toViews = new int[] { R.id.row_ID, R.id.name, R.id.email };
    db.openDatabase();
    @SuppressWarnings("deprecation")
    SimpleCursorAdapter sCAdapter = new SimpleCursorAdapter(this,
            R.layout.table_row, db.getContacts(), fromColumns, toViews);
    sCAdapter.setViewResource(R.layout.table_row);
    gv.setAdapter(sCAdapter);
    db.closeDatabase();
}

...以及读取与 chebox 位于同一记录中的 ROW_ID 值的方法(我总是得到第一个 ROW_ID 的值,无论我触摸第一个、第二个还是第 n 个复选框,这就是问题!):

    public void x(View view) {
    TextView tv = (TextView) findViewById(R.id.row_ID);

    recordIds.add(Long.valueOf(tv.getText().toString()));
    long[] longArray = new long[recordIds.size()];
    for (int i = 0; i < recordIds.size(); i++) {
        longArray[i] = recordIds.get(i);
        Toast.makeText(this, String.valueOf(longArray[i]),Toast.LENGTH_LONG).show();

    }
}

提前感谢您,抱歉打扰您,Erik D.

add1 (1. 编辑)

亲爱的朋友们!非常感谢大家的回答,但不幸的是,这些建议对我不起作用。让我发布整个代码,我用“setOnItemClickListener(new OnItemClickListener()”改变了它。它仍然不起作用......如果有人有空闲时间看,我将发布整个代码(xml和java)它——我不知道出了什么问题。

* *activity_main.xml**

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right" >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="20dp"
        android:numColumns="3" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:ems="10"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/gridView1"
        android:layout_toLeftOf="@+id/button1"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:onClick="AddRecord"
        android:text="Insert" />

</RelativeLayout>

* *table_row.xml**

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

    <TableRow>

        <TextView
            android:id="@+id/row_ID"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:padding="5px"
            android:textSize="22dp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:padding="5px"
            android:textSize="22dp" />

        <TextView
            android:id="@+id/email"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:clickable="true"
            android:padding="5px"
            android:textSize="22dp" />

        <CheckBox
            android:id="@+id/chk"
            android:layout_width="10px"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </TableRow>

</TableLayout>

* MainActivity.java *

> package net.learn2develop.databases;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    DBAdapter db;
    EditText name, mail;
    GridView gv;
    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText) findViewById(R.id.editText1);
        mail = (EditText) findViewById(R.id.editText2);
        db = new DBAdapter(this);
        gv = (GridView) findViewById(R.id.gridView1);
        showGridData();
    }

    public void AddRecord(View view) {
        if (!(name.getText().toString().isEmpty())
                && !(mail.getText().toString().isEmpty())) {
            db.openDatabase();
            if (db.insertContact(name.getText().toString(), mail.getText()
                    .toString()) >= 0) {
                showMessage("Record added succesfully!", "Inserting...");
                db.closeDatabase();
                showGridData();
            }
        } else {
            showMessage("You can't add empty record!", "Inserting...");
        }
    }

    public void showGridData() {
        String[] fromColumns = { db.KEY_ROWID, db.KEY_NAME, db.KEY_EMAIL };
        int[] toViews = new int[] { R.id.row_ID, R.id.name, R.id.email };
        db.openDatabase();
        SimpleCursorAdapter sCAdapter = new SimpleCursorAdapter(this,
                R.layout.table_row, db.getContacts(), fromColumns, toViews);
        sCAdapter.setViewResource(R.layout.table_row);
        gv.setAdapter(sCAdapter);
        // Implement On Item click listener
        gv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Toast.makeText(getApplicationContext(),
                        ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }
        });
        db.closeDatabase();
    }

    public void showMessage(String message, String source) {
        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
        dlgAlert.setCancelable(false);
        dlgAlert.setMessage(message);
        dlgAlert.setTitle(source);
        dlgAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }
}

* DBAdapter.java *

    package net.learn2develop.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "_id";
    static final String KEY_NAME = "name";
    static final String KEY_EMAIL = "email";
    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "MyDB";
    static final String DATABASE_TABLE = "contacts";
    static final int DATABASE_VERSION = 1;

    static final String DATABASE_CREATE = "create table " + DATABASE_TABLE
            + " (" + KEY_ROWID + " integer primary key autoincrement, "
            + KEY_NAME + " text not null, " + KEY_EMAIL + " text not null);";

    final Context context;

    DatabaseHelper DBHelper;
    SQLiteDatabase db;

    public DBAdapter(Context ctx) {// CONSTRUCTOR!!
        this.context = ctx;

        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    public DBAdapter openDatabase() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    public void closeDatabase() {
        DBHelper.close();
    }

    public long insertContact(String name, String email) {

        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    public boolean deleteContact(long rowId) {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor getContacts() {
        return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME,
                KEY_EMAIL }, null, null, null, null, null);
    }

    public Cursor getContact(long rowId) throws SQLException {

        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_NAME, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
                null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateContact(long rowId, String name, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_EMAIL, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

亲爱的朋友们,再次提前感谢您,Erik D.

4

3 回答 3

1

您可以使用setTag和类的getTag方法View将一条信息与您的视图联系起来。

于 2013-09-12T22:26:05.247 回答
1

您需要实现 ItemClickListener。onItemClick 将为网格视图中单击的每个项目调用并提供单击的位置。

检查示例代码以了解如何实现它。从适配器获取此位置数据。

于 2013-09-12T22:35:10.313 回答
0

我找到了问题的根源 - 基本上,它所要做的就是定义 GridView 的视图元素: android:focusable="false" android:focusableInTouchMode="false" 例如:

<TextView
    android:id="@+id/row_ID"
    android:layout_width="50px"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:textSize="20dp" />

使用这两个参数的 GridView 元素不会窃取网格的焦点,并且侦听器会在网格上工作。

玩得开心,Erik D.

于 2013-09-13T23:32:31.247 回答