3

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?

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

halfer
  • 19,824
  • 17
  • 99
  • 186
hectichavana
  • 1,436
  • 13
  • 41
  • 71

1 Answers1

9

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

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));

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

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.

rekaszeru
  • 19,130
  • 7
  • 59
  • 73