我正在尝试在某种情况出现时将Xml中View定义的行动态更改为1dp
<View
android:id="@+id/line"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:background="#000000" />
如何获取此视图,以便我可以动态更改其高度?
对于ImageView我使用
public ImageView theImage;
....
public MyViewHolder(View itemView) {
super(itemView);
theImage = (ImageView) itemView.findViewById(R.id.icon);
**and then whatever condition**
}
但是如果
public ImageView theImage;
public View theLine;
...
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
theImage = (ImageView) itemView.findViewById(R.id.icon);
theLine = (View) itemView.findViewById(R.id.line);
**and then whatever condition change the height to 1dp**
}
我得到灰色(查看),投射'itemView.findViewById(R.id.line)'到'查看'是多余的
我认为(View)不能以这种方式使用
由于
答案 0 :(得分:2)
强制转换是多余的,因为findViewById始终返回一个View对象。你可以将(视图)转换为无效,但在这种情况下它没有意义,所以你也可以摆脱它。
如果您正在查找TextView,则需要进行强制转换。有关详细信息,请参阅casting objects小节。
答案 1 :(得分:2)
您应该转到findViewById
方法的定义。签名如下:
public View findViewById(int);
如您所见,返回类型为View
。当方法的返回值不是您想要的类型时,您只需要一个强制转换(那是(View)findViewById(R.id.line)
东西)。例如,如果您想要ImageView
,但返回值类型为View
,则需要执行以下操作:
(ImageView)findViewById (R.id.image);
Casting采用以下形式:
(Type1)value1
这将返回Type1
的值,但value1
的类型必须与Type1
兼容才能执行此操作。如果您想了解更多信息,可以在谷歌上搜索Java Casting。
答案 2 :(得分:2)
您不应该转换视图,因为它已经返回了View。 解决方案?试试这个:
theLine = itemView.findViewById(R.id.line);
答案 3 :(得分:1)
findViewById
返回View
这就是为什么它告诉您不需要将其强制转换为View
,因为您要将View
对象转换为View
虽然ImageView
是View
的子类,但您需要进行转换。