Android中带有传递参数的Click侦听器方法

Android中带有传递参数的Click侦听器方法

本文介绍了Android中带有传递参数的Click侦听器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android和Java的新手.我想制作一个带有int参数的onClick方法,所以这是我的尝试:

I'm new to android and Java. I want to make an onClick method which carries an int argument, so this is my attempt:

public void randomClick(final int randomIndex)
    {
      private OnClickListener top_listener = new OnClickListener() {
        public void onClick(View v) {
                    Intent top = new Intent(Main.this, ProjectDetail.class);
                    top.putExtra("spendino.de.ProjectDetail.position", randomIndex);
                    startActivity(top);
        }
        };
    }

但是它仍然包含错误,有人可以为我修复吗?

but it still contains error, can anybody fix that for me?

稍后我要将方法设置为ImageView,它或多或少看起来像这样 image1.randomClick(randomIndex1); .

Later I want set the method to an ImageView, it will look more or less like this image1.randomClick(randomIndex1);.

推荐答案

当前,在您的实现中, OnClickListener 未绑定到任何视图,因此不会被触发.

Currently in your implementation the OnClickListener is not bounded to any view, so it won't get fired.

您应该创建自己的(可能是内部的,但不是匿名的)类,以实现 OnClickListener 接口:

You should create your own (might be inner but not anonymous) class implementing the OnClickListener interface:

public class RandomClickListener implements View.OnClickListener
{
    private final int randomIndex;

    public RandomClickListener(final int randomIndex)
    {
        this.randomIndex = randomIndex;
    }
    @Override
    public void onClick(View v)
    {
        Intent top = new Intent(Main.this, ProjectDetail.class);
        top.putExtra("spendino.de.ProjectDetail.position", randomIndex);
        startActivity(top);
    }
}
[...]
image1.setOnClickListener(new RandomClickListener(randomIndex));

这样,当您单击 image1 时,它将使用上面设置的 randomIndex 启动 ProjectDetail 活动.

This way when you click on the image1 it will start the ProjectDetail activity with the randomIndex set above.

如果您想显式启动 ProjectDetails 活动(无需任何用户交互(例如单击)),则完全不需要 OnClickListener .

If you'd like to explicitly start the ProjectDetails activity (without any user interactions such as a click), you don't need an OnClickListener at all.

这篇关于Android中带有传递参数的Click侦听器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:23