单击时无法在gridview上选择行?

时间:2014-01-21 15:36:02

标签: android

这是从sqlite数据库获取数据并将其显示在gridview上的代码....

然而,我试图让选定的项目“整行”,但我没有成功

  protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SearchV = (SearchView) findViewById(R.id.searchView1);

    data = (GridView) findViewById(R.id.gridView1);
    List<String> Ldata = new ArrayList<String>();
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,Ldata);
    dataAdapter.setDropDownViewResource(R.layout.activity_main);
    try
    {
        db = openOrCreateDatabase("mydb",MODE_PRIVATE,null);
        Cursor c = db.rawQuery("select * from Names", null);
        if (c != null)
        {
        if (c.moveToFirst())
        {
            do
            {
                String id = c.getString(c.getColumnIndex("id_num"));
                String fname = c.getString(c.getColumnIndex("fname"));
                String mname = c.getString(c.getColumnIndex("mname"));
                String lname = c.getString(c.getColumnIndex("lname"));
                Ldata.add(id);
                Ldata.add(fname);
                Ldata.add(mname);
                Ldata.add(lname);
                data.setAdapter(dataAdapter);
            }
            while(c.moveToNext());
        }
        }
        else
        {
            Toast.makeText(getApplicationContext(), "no data Available", Toast.LENGTH_SHORT).show();
        }
    }
    catch (Exception e)
    {
        Toast.makeText(getApplicationContext(), "Error Retrieving Data", Toast.LENGTH_SHORT).show();
    }
    db.close();

    //Toast.makeText(this,"test "+ data.getSelectedItem(), Toast.LENGTH_SHORT).show();
    data.setOnItemClickListener(this);

此代码更改所选项目的背景。 但是,如何选择整行?并在行的第一个单元格中获取文本?

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    //Toast.makeText(this, "test "+ arg0, Toast.LENGTH_SHORT).show();

    // change color of selected cell in gridview
    data.getChildAt(arg2).setBackgroundColor(Color.RED);
    Toast.makeText(this, "test " , Toast.LENGTH_SHORT).show();

}

1 个答案:

答案 0 :(得分:0)

尝试自定义适配器。它会起作用