2

I wanted to use a function that used a arraylist for multiple types of arraylists, but I don't know how to do that.

ArrayList<TextView> List2 = new ArrayList<>();
ArrayList<View> List1 = new ArrayList<>();

ChangeTextSize(List1);
ChangeTextSize(List2);

public void ChangeTextSize(ArrayList List){
        for (int i = 0; i < List.size(); i++){
            List.get(i).setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
   }
}

-Edit: The function is meant for any view. I'm now aware that setTextSize isn't allowed for view.

2
  • Since View doesn't have a setTextSize method, it wouldn't make sense. However, if you change the method call to public void ChangeTextSize(ArrayList<TextView> List){ you'd be able to pass List1 with less issues Commented Mar 9, 2018 at 4:35
  • Please see: How do I avoid misusing tags? Commented Mar 9, 2018 at 4:38

2 Answers 2

2

If you want to change the text size using the function setTextSize the object which you call the function on has to be a TextView because that object has the function. A View doesn't have the function setTextSize so that won't work.

But if you have a function that both TextView and View have; for example setBackgroundColor you can do it like this:

public void changeBackgroundColor(ArrayList<? extends View> list) {
  for (View v: list) {
    v.setBackgroundColor(Color.red);
  }
}

So basically you give your list argument a generic; meaning in this case: "all the element in the list should be a view or sub-class thereof". So the methods you can call on the element from this list are all methods available in the View class.

But if you want to change text-sizes your function needs to accept a list of TextView (or sub-classes thereof), like this:

public void changeTextSize(ArrayList<? extends TextView> list) {
  for (TextView tv: list) {
    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Is this Android?

You can use a wild card to allow a range of type-parameters. Something like:

public void ChangeTextSize(ArrayList<? extends TextView> list){
        for (int i = 0; i < list.size(); i++){
            list.get(i).setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
   }
}

But I don't see that View has a method setTextSize so obviously that type can't be used here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.