Android错误将上下文传递给OnClick内的Cursor Adapter(视图视图)

时间:2012-02-13 16:33:28

标签: android android-fragments android-adapter

在片段中,我有一个按钮,我想使用光标适配器从数据库“触发”填充Listview。

片段的代码如下:

public class TabFragment6 extends ListFragment {
/** (non-Javadoc)
 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
 */



         @Override
         public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);


         }


         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {

             LinearLayout Layout6 = (LinearLayout) inflater.inflate(R.layout.tab_frag6_layout, container, false);

            // Register for the Button.OnClick event 
                Button bShopGuit = (Button)Layout6.findViewById(R.id.buttonshopguit);
                bShopGuit.setOnClickListener(new View.OnClickListener() {           //abre setonclicklistener(
                    @Override
                    public void onClick(View v) {


                        Cursor allItems;
                        MyDatabase db;

                        Context ctx = (Context)TabFragment6.this.getActivity();


                        db = new MyDatabase(ctx);
                        allItems = db.getGuitarItems();


                        ListAdapter adapter = new SimpleCursorAdapter (ctx, 
                                android.R.layout.simple_list_item_1, 
                                allItems, 
                                new String[] {"ItemName"}, 
                                new int[] {android.R.id.text1});

                        getListView().setAdapter(adapter);  
                    }
                });                                                                 //fecha )




          return Layout6;
         }

但是,我在适配器中收到错误:方法getactivity()未定义类型new View.OnClickListener(){}

我该如何解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:3)

使用此 db = new MyDatabase(getActivity()); 而不是上下文ctx =(上下文)TabFragment6.this.getActivity(); db = new MyDatabase(ctx);

答案 1 :(得分:1)

您无法在getActivity()界面中呼叫new View.OnClickListener() { 因为那里没有这种方法。您可能想要创建最终参考 您的活动并在您的onClick()方法中使用它。

您正在创建一个新的匿名类,它实现了View.OnClickListener接口 没有getActivity()方法。

应该是这样的:

@Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {

             LinearLayout Layout6 = (LinearLayout) inflater.inflate(R.layout.tab_frag6_layout, container, false);
     final Activity activity = this.getActivity(); //this will call your tabfragment's associated activity 


     ............
 //and in your onClick()
             db = new MyDatabase(activity); // or try to use the Contexts or cast to them depends on your constructor parameters            

希望有所帮助