How to pass drawable file as parameter?

Asked

Viewed 146 times

0

I have a problem that should be simple, I want to move to another Ctivity, a drawable as parameter.

here is my Onclick function:

img1.setOnClickListener(new View.OnClickListener(){
    @Override
       public void onClick(View v){
        Intent it = new Intent(List.this, StoryActivity.class);
        Drawable d = getResources().getDrawable();
        it.putExtras();
        startActivity(it);
        }
    });

For example, I have an image file called img1.jpg.

I want this function to pass to the other Activity this parameter, so that once the second Activity is triggered it knows which file to show.

1 answer

1


Instead of you passing Drawable as a parameter, you can only pass the Resource ID and then instantiate Drawable in the other Activity using this Resource ID. It is good to know that passing an object from one Activity to another requires the execution of Serialization, which can be costly depending on the size and complexity of the serialized object.

What you can do is the following:

On your Activity that will send the drawable

img1.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v){

        Intent it = new Intent(List.this, StoryActivity.class);
        int drawableId = //R.drawable.meu_drawable_id
        it.putExtra("drawable_id", drawableId);
        startActivity(it);
    }
});

On your Activity you will receive the drawable

@Override
protected void onCreate(){

    /*...*/

    Intent intent = getIntent();
    int drawableId = intent.getIntExtra("drawable_id", 0); // 0 é apenas um valor default caso o drawableId não seja passado

    Drawable meuDrawable = getResources().getDrawable(drawableId);

   /*...*/
}
  • I left it like this: int drawable = //R.drawable.img1 When I defined putExtras the way I said it returned an error saying: "Cannot resolve method 'putExtras(java.lang.String, int)'

  • 1

    The only modification I had to make was in "it.puExtra(...);"

  • @felipe218 , well noted, I wrote the wrong method. The correct is to use putExtra() and not putExtras()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.