Android cannot find method from button's onClick in ListView Row

后端 未结 4 1908
甜味超标
甜味超标 2021-01-18 23:10

I have a ListView populated from a custom adapter. Each row has 1 button in it. In the xml the button has the onClick attribute passed. I have only the xml, not any OnClickL

4条回答
  •  失恋的感觉
    2021-01-18 23:53

    It’s important that MyActivity and getContext() of CustomAdapter must be the same instance. Compare yours with mine.

    My codes:

    MyActivity.java

    public class MyActivity extends Activity {
        public static final String TAG = "MyActivity";
        private ListView mListView;
        private CustomAdapter mAdapter;
        private ArrayList mData;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
    
            mListView = (ListView) findViewById(R.id.listView);
    
            mData = new ArrayList();
            mData.add("111");
            mData.add("222");
            mData.add("333");
            mData.add("444");
            mData.add("555");
    
            mAdapter = new CustomAdapter(this, R.layout.list_item_view, mData);
            mListView.setAdapter(mAdapter);
        }
    
        public void onClickHandler(View view) {
            Log.i(TAG, "onClickHandler()");
        }
    }
    

    CustomAdapter.java

    public class CustomAdapter extends ArrayAdapter {
    
        public CustomAdapter(Context context, int resource, ArrayList objects) {
            super(context, resource, objects);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.list_item_view, null);
            }
    
            return convertView;
        }
    }
    

    activity_my.xml

    
    
        
    
    
    

    list_item_view.xml

    
    
    
        

提交回复
热议问题