安卓:点击监听器方法传递参数 [英] Android: Click listener method with passing argument

查看:197
本文介绍了安卓:点击监听器方法传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和Java。我想要做一个onClick方法,它带有一个int参数,所以这是我的尝试:

I'm new to android and Java. I wanna 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);

非常感谢你。我愿意接受任何形式的解决方案。

Thank you very much. I'm open to any kind of solution.

推荐答案

目前在实施 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));

当你点击此搜索将开始与 ProjectDetail 活动这种方式> randomIndex 上面设置。

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.

这篇关于安卓:点击监听器方法传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆