Android在MainActivity中调用自定义适配器方法

时间:2018-09-11 19:38:50

标签: java android

以下代码存在于我的主要活动中。我想知道它们是否是一种方法,我可以使用传递到gridview.setAdapter()函数中的GridAdapter实例来调用方法。

GridAdapter负责用图像填充gridview。在单击时,我想获得它的位置以及GridAdapter中的一些数据。

    // create a new GridView object
    GridView gridview = this.findViewById(R.id.gridView);
    gridview.setAdapter(new GridAdapter(this));
    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id)
        {
            thisGridAdapter.someMethod(position);  //what I want to do
            Log.d("gridView", String.valueOf(position));
            TextView tv = findViewById(R.id.textView);
            tv.setText(String.valueOf(position));
        }
    });

1 个答案:

答案 0 :(得分:1)

将其分配给变量吗?

final GridAdapter adapter = new GridAdapter(this);
GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        adapter.someMethod(position);
    }
});

或者,使用GridView#getAdapter()方法并将其强制转换为适配器类:

final GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(new GridAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        ((GridAdapter) gridView.getAdapter).someMethod(position);
    }
});