在listItem onclick动作中实现按钮onclick

时间:2013-11-15 17:34:40

标签: android android-listview

我从数据库中挑选了一些数据,然后在列表视图中显示它们。 在我的listview中,我有一个textview和每个列表项的按钮。 我希望每当点击列表项的按钮时,它将显示来自listitem的相应文本视图的文本。

用于实现列表项按钮操作的mycode就是这样。

       final TestAdapter mDbHelper = new TestAdapter(this);        
    mDbHelper.createDatabase();      

    EditText word_from_box;
    //ListView mylist ;
    //SimpleAdapter adapter;

    word_from_box=(EditText) findViewById(R.id.editText1);
     final ListView listView = (ListView) findViewById(R.id.mylist);

 listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
         public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
            // TODO Auto-generated method stub

            Toast.makeText(getApplicationContext(),"Clicked a list item ", Toast.LENGTH_SHORT).show();

            Button fav_b=(Button) findViewById(R.id.fav_btn);
            fav_b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),"clicked on button on a listview ", Toast.LENGTH_SHORT).show();
                }
            });

        }
    });

以及将数据显示在数据库列表视图中的代码就是这样:

mDbHelper.open();

            String ss=s.toString();

             ArrayList<HashMap<String, String>> list_of_wordmeanings = new ArrayList<HashMap<String, String>>();

            Cursor mCursor = mDbHelper.getTestData(ss);

            for (int i = 0; i < mCursor.getCount(); i++) 
            {
                mCursor.moveToPosition(i);

                String string = mCursor.getString(1);

                HashMap<String, String> hm = new HashMap<String, String>();

                    String word = mCursor.getString(0).toString();
                    String meaning = mCursor.getString(1).toString();

                      hm.put("key_word",word);
                      hm.put("key_meaning",meaning);

                      list_of_wordmeanings.add(hm);
            }


               // Keys used in Hashmap
                    String[] from = { "key_word","key_meaning" };
                 // Ids of views in listview_layout
                    int[] to = { R.id.txt1,R.id.txt2};
                 // Instantiating an adapter to store each items
                    // R.layout.listview_layout defines the layout of each item
                    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), list_of_wordmeanings, R.layout.list_layout, from, to);
                 // adapter=new SimpleAdapter(this,list_of_reg_info,R.layout.list_layout,new String[] { "key_name","key_password" },new int[] { R.id.text1, R.id.text2 });
                 // Setting the adapter to the listView
                    listView.setAdapter(adapter);

但是当我点击listview的项目时它不起作用,当我点击列表项目上的按钮时它也不起作用。 我怎么能这样做?

N:B:我的TestAdapter类是:

protected static final String TAG = "DataAdapter";

private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

public TestAdapter(Context context) 
{
    this.mContext = context;
    mDbHelper = new DataBaseHelper(mContext);
}

public TestAdapter createDatabase() throws SQLException 
{
    try 
    {
        mDbHelper.createDataBase();
    } 
    catch (IOException mIOException) 
    {
        Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
        throw new Error("UnableToCreateDatabase");
    }
    return this;
}




public TestAdapter open() throws SQLException 
{
    try 
    {
        mDbHelper.openDataBase();
        mDbHelper.close();
        mDb = mDbHelper.getReadableDatabase();
    } 
    catch (SQLException mSQLException) 
    {
        Log.e(TAG, "open >>"+ mSQLException.toString());
        throw mSQLException;
    }
    return this;
}





public void close() 
{
    mDbHelper.close();
}




 public Cursor getTestData(String s)
 {
     try
     {

     //String sql ="SELECT * FROM Table1 LIMIT 5";//"SELECT  * FROM " + TABLE_REGISTRATION +" WHERE "+ KEY_NAME +" LIKE '"+ s +"%'" ;

         String sql ="SELECT  * FROM dic WHERE english LIKE '"+ s +"%' LIMIT 5" ;

         Cursor mCur = mDb.rawQuery(sql, null);
         if (mCur!=null)
         {
            mCur.moveToNext();
         }
         return mCur;
     }
     catch (SQLException mSQLException) 
     {
         Log.e(TAG, "getTestData >>"+ mSQLException.toString());
         throw mSQLException;
     }
 }

1 个答案:

答案 0 :(得分:2)

您可以在适配器类的getView中执行此操作。在适配器getView中为您的按钮实现OnClickListener

在getView中

holder.button.setOnClickListener(mClickListener);
holder.button.setTag(holder.tv.getText());

然后

private OnClickListener mClickListener = new OnClickListener() {

 public void onClick(View v) {

        Toast.makeText(getApplicationContext(),"Text is"+v.getTag(),Toast.LENGTH_SHORT).show();
  }
};

编辑:

CustomAdapter cus = new CustomAdapter(MainActivity.this, list_of_wordmeanings);
listview.setAdapter(cus);

CustomAdapter

public class CustomAdapter extends BaseAdapter
{

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return items.size();
    }
    LayoutInflater inflater;
    Context mContext;
     ArrayList<HashMap<String,String>> items;
    public CustomAdapter(Context context, ArrayList<HashMap<String,String>> List) {

        // TODO Auto-generated constructor stub
        inflater = LayoutInflater.from(context);
        mContext = context;
        items= List;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;
        if(convertView==null)
        {
        convertView = inflater.inflate(R.layout.list_item, parent,false);
        holder = new ViewHolder();
        holder.tv = (TextView) convertView.findViewById(R.id.textView1);
        holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
        holder.b1 = (Button) convertView.findViewById(R.id.button1);
        holder.b2 = (Button) convertView.findViewById(R.id.button2);
        convertView.setTag(holder); 
    } else { 
        holder = (ViewHolder) convertView.getTag(); 
    } 
        HashMap<String,String> map = items.get(position);
        holder.tv.setText(map.get("key_word"));
        holder.tv2.setText(map.get("key_meaning"));
        holder.b1.setOnClickListener(mClickListener);
        holder.b1.setTag(holder.tv.getText());
        holder.b2.setOnClickListener(mClickListener);
        holder.b2.setTag(holder.tv2.getText());
        return convertView;
    }
    private OnClickListener mClickListener = new OnClickListener() {

         public void onClick(View v) {
             switch(v.getId())
             {
             case R.id.button1 :
                 Toast.makeText(mContext,"Text is"+v.getTag(),Toast.LENGTH_SHORT).show();
                 break;
             case R.id.button2 :
                 Toast.makeText(mContext,"Text is"+v.getTag(),Toast.LENGTH_SHORT).show();
             break;
             }

          }
        };
static class ViewHolder
{
    TextView tv,tv2;
    Button b1,b2;

}
@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}
}

list_item.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="36dp"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView1"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="25dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Button2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_toLeftOf="@+id/button1"
        android:text="TextView" />

</RelativeLayout>