我想使用一个将数组列表用于多种类型数组列表的函数,但我不知道该怎么做。
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);
}
}
-编辑:该功能适用于任何 View 。我现在知道 setTextSize 不允许查看。
最佳答案
如果您想使用函数 setTextSize
更改文本大小,则调用该函数的对象必须是 TextView
,因为该对象具有 function 。 View
没有 setTextSize
函数,因此它不起作用。
但是如果你有一个 TextView
和 View
都有的功能;例如 setBackgroundColor
你可以这样做:
public void changeBackgroundColor(ArrayList<? extends View> list) {
for (View v: list) {
v.setBackgroundColor(Color.red);
}
}
所以基本上你给你的 list
参数一个泛型;在这种情况下意味着:“列表中的所有元素都应该是 View 或其子类”。因此,您可以对该列表中的元素调用的方法都是 View
类中可用的方法。
但是,如果您想更改文本大小,您的函数需要接受 TextView
(或其子类)列表,如下所示:
public void changeTextSize(ArrayList<? extends TextView> list) {
for (TextView tv: list) {
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
}
}
关于Java - ArrayList<E> 函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49186610/