Android: pass a resource id as a parameter

11,535

Solution 1

Resource id - is an integer value. Just pass an int:

private void translateRight(int resource){
    ImageView img = (ImageView) findViewById(resource);
    //stuff
}

Solution 2

Resource ID is an integer, not a String.

Solution 3

  1. The second approach is that you directly pass the findViewById

    boolean tvStatus=status((CheckBox)findViewById(R.id.vn));

      public boolean status(CheckBox ch)
         {
    
             boolean ll=ch.isChecked() ;
             return  ll;
         }
    
Share:
11,535
cyclingIsBetter
Author by

cyclingIsBetter

Updated on July 17, 2022

Comments

  • cyclingIsBetter
    cyclingIsBetter almost 2 years

    I have this code:

    translateRight("iv1"); //iv1 is an id of an imageView
    
        private void translateRight(String st){
    
        ImageView img = (ImageView)findViewById(R.id.st);
            Animation a = AnimationUtils.loadAnimation(this, R.anim.translate_right);
            img.startAnimation(a);
        }
    

    I have "translateRight" that is a method that show an animation, but at this method I should pass a resource id; I tried with a string but it don't work, what can I do?

    • Dmitry Zaytsev
      Dmitry Zaytsev over 11 years
      By the way - it's more convinient to pass ImageView itself.
  • fcdt
    fcdt over 3 years
    Welcome to StackOverflow. Please do not post another answer if you want to update your existing answer, use the edit button instead.
  • Nikhil Bansal
    Nikhil Bansal over 3 years
    Just adding on to this answer, the function accepts any integer value right now. So, if you pass -13 or some arbitrary number, it will accept it and will try to find a view with that id. This can be handled by adding @IdRes annotation in the parameter. This will ensure that only a R.id type int is sent at compile time.