2012-01-31 156 views
1

我想创建一个自定义适配器,以便在每个列表项中都有可点击的按钮。 我的问题是,即时通讯从数据库中获取数据,我不知道如何使用我的自定义adapter.This是我的适配器代码将它们在列表中:Android自定义适配器

public class Adapter extends SimpleCursorAdapter { 
    private Context mContext; 

    final Drawable delete; 
    private ImageButton imageButton2; 

    private LayoutInflater inflater; 

    private int favoriteListRow; 

    public Adapter(Context ctx, int favoriteListRow, Cursor cursor, 
      String[] columns, int[] to) { 
     super(ctx, favoriteListRow, cursor, columns, to); 

     mContext = ctx; 
     inflater = LayoutInflater.from(mContext); 

     delete_btn = ctx.getResources().getDrawable(R.drawable.delete); 

     DB entry = new DB(ctx); 
     entry.open(); 
     cursor = entry.getData(); 
     columns = new String[] { DBHelper.NAME, DBHelper.NAME2 }; 
     to = new int[] { R.id.textView01, R.id.textView02 }; 
     entry.close(); 

    } 

    public View getView(Context context, Cursor cursor, ViewGroup parent) { 

     final LayoutInflater inflater = LayoutInflater.from(mContext); 

     View v = inflater.inflate(R.layout.row, parent, false); 

     TextView name_text = (TextView) v.findViewById(R.id.textView01); 

     int nameCol = cursor.getColumnIndex(DBHelper.NAME); 

     String name = cursor.getString(nameCol); 
     name_text.setText(name); 

     TextView name2_text = (TextView) v.findViewById(R.id.textView02); 
     int theCol = cursor.getColumnIndex(DBHelper.NAME2); 

     String the = cursor.getString(theCol); 
     the_text.setText(the); 

     imageButton2 = (ImageButton) v.findViewById(R.id.delete_btn); 
     imageButton2.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG) 
         .show(); 

      } 
     }); 

     return v; 
    } 



} 

然后从我的主要活动即时调用适配器:

Adapter adapter; 

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

     list.setAdapter(adapter); 
+0

你有任何问题,你的初始化吹气布局?看来你在正确的轨道上。 – kosa 2012-01-31 15:24:49

+0

是的,因为你现在看到我的代码即时得到这个错误java.lang.ClassCastException:android.widget.LinearLayout $ LayoutParams不能转换为android.widget.AbsListView $ LayoutParams – 2012-01-31 15:27:34

+0

是否正确读取适配器类中的我的数据库数据?或者我应该更好地阅读我的主要内容? – 2012-01-31 15:28:08

回答

0

尝试使用这一行,而不是

LayoutInflater inflater = (LayoutInflater)context.getSystemService 
    (Context.LAYOUT_INFLATER_SERVICE); 
+0

我将其替换为im没有得到这个错误。但我仍然没有结果出现在我的列表中 – 2012-01-31 16:12:12

+0

看起来你在设置它之前没有初始化你的适配器 – SeanPONeil 2012-01-31 22:45:51