2012-05-21 31 views
5

Tôi đang mắc kẹt với việc tạo bộ điều hợp tùy chỉnh. Tôi muốn setOnClickListener trên các nút bên trong ListView và tôi tìm thấy chủ đề này trông ok how-to-setonclicklistener-on-the-button-inside-the-listview nhưng vấn đề là tôi nhận được lỗi mã không thể truy cập trên dòng getLayoutInflater.getLayoutInflater bên trong tùy chỉnh simpleCursorAdapter

đây là mã của tôi

public class MyCursorAdapter extends SimpleCursorAdapter{ 

    private final Context ctx; 
    private Button tagButton = null; 

    public MyCursorAdapter(Context context, int layout, Cursor c, 
      String[] from, int[] to) { 
     super(context, layout, c, from, to); 
     ctx = context; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     return super.getView(position, convertView, parent); 
     LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = li.inflate(R.layout.tags_list_element, null, true); 
     tagButton= (Button)rowView.findViewById(R.id.tag_title); 
     tagButton.setTag(position); 

     tagButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
      } 
     }); 
     return rowView; 

    } 

} 

cả hai phương pháp không làm việc cho tôi

LayoutInflater inflater = context.getLayoutInflater(); 

LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
+0

Can u plz cho tôi lỗi Log ........... – c2dm

Trả lời

11

Hãy thử:

View myView = LayoutInflater.from(ctx).inflate(R.layout.my_view, null); 

Hơn nữa, bạn nhận được ngoại lệ nào?


Chỉnh sửa: Trong phương thức "getView", dòng đầu tiên là "return .....", vì vậy phần còn lại của phương thức của bạn sẽ không bao giờ được thực hiện, tôi nghĩ ....;)

+0

Ye tôi đã bỏ lỡ lợi nhuận trên đầu .. Cảm ơn;) – Greg

2

Từ quan điểm thực hiện xem:

View myView = LayoutInflater.from(context).inflate(R.layout.my_view, parent, false); 

là chính xác; nhưng nó hiệu quả hơn để lưu trữ các inflater trong một lĩnh vực cuối cùng bên trong bộ chuyển đổi.

private final Context ctx; 
private final LayoutInflater mInflater; 
private Button tagButton = null; 

public MyCursorAdapter(Context context, int layout, Cursor c, 
      String[] from, int[] to) { 
    super(context, layout, c, from, to); 
    ctx = context; 
    mInflater = LayoutInflater.from(ctx); 
} 

Sau đó, thực hiện thao tác getView của bạn.

//.... 
final View v = mInflater.inflate(R.layout.list_item, parent, false); 
//.... 
//stuff here 
// 
return v; 

CSONG đảm bảo bạn Bối cảnh là bối cảnh hoạt động của bạn, bạn sẽ gặp vấn đề Theming nếu bạn sử dụng ngữ cảnh sai.

Kính trọng, Chris

Các vấn đề liên quan