gpt4 book ai didi

android - 如何从 Android 应用程序的 GridView 中的元素获取值?

转载 作者:太空狗 更新时间:2023-10-29 13:28:30 24 4
gpt4 key购买 nike

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

以下是布局 XML 文件和代码的 fragment ,其中我使用 SimpleCursorAdapter 调整光标:ma​​in.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();
}

...以及读取与定位复选框相同的记录中的 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();

}
}

在此先感谢您,抱歉打扰您,问候,埃里克 D.

add1(1.编辑)

亲爱的 friend 们!非常感谢大家的回答,但不幸的是这个建议对我不起作用。让我发布完整的代码,我用“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;
}
}

亲爱的 friend 们,再次提前致谢,问候,埃里克 D.

最佳答案

您可以使用 View 类的 setTaggetTag 方法将一条信息关联到您的 View 。

关于android - 如何从 Android 应用程序的 GridView 中的元素获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18775268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com