【问题标题】:How can I make findViewById get the id attibute on the XML dynamically (Android)?如何让 findViewById 动态获取 XML 上的 id 属性(Android)?
【发布时间】:2011-11-10 19:51:19
【问题描述】:

通常你会这样:

        Activity parent = (Activity) context;
                dragImage = (ImageView) parent.findViewById(R.id.what_ever_you_defined_on_xml);

但是,在我的情况下,我希望“findViewById”动态地获取 id 属性,因为我有多个属性,具体取决于用户想要在地图上使用哪种 OverlayItem(打开街道地图)。我已经尝试过了,但我的应用程序崩溃了:

        Activity parent = (Activity) context;
                View v = parent.getCurrentFocus();  
    dragImage = (ImageView) parent.findViewById(v.getId());

有什么建议吗?谢谢。


添加上下文的更多细节:

public Itemizedoverlay(Drawable defaultMarker, Context context, MapView map) {

super(defaultMarker, new DefaultResourceProxyImpl(context));
this.defaultMarker = defaultMarker;

this.map = map;

// Setup for dragging:
// Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle):

Activity parent = (Activity) context;
View v = parent.getCurrentFocus();  
dragImage = (ImageView) parent.findViewById(v.getId());

xDragImageOffset = dragImage.getDrawable().getIntrinsicWidth() / 2;
yDragImageOffset = dragImage.getDrawable().getIntrinsicHeight();
}

在 XML 中:

<ImageView 
    android:id="@+id/drag1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/symbol1"
    android:visibility="gone"
    /> 

    <ImageView 
    android:id="@+id/drag2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/symbol2"
    android:visibility="gone" />

    <ImageView 
    android:id="@+id/drag3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/symbol3"
    android:visibility="gone"
    /> 

    <ImageView 
    android:id="@+id/drag4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/symbol4"
    android:visibility="gone"
    /> 

【问题讨论】:

    标签: android xml view itemizedoverlay


    【解决方案1】:

    您的最终结果不会与以下内容相同:

    dragImage = (ImageView)v;
    

    【讨论】:

    • 史蒂夫,谢谢你的建议。我已经尝试过您的建议(向下转换),但应用程序仍然崩溃。
    • 被聚焦的项目不是 ImageView
    • 你能详细说明你的答案吗?我还不清楚。顺便说一句,我正在运行调试器,它说 v 是空的,所以 dragImage 什么都没有。
    • 好的,你能发布更多代码然后提供更多上下文吗?也许在对 dragImage 做任何事情之前进行一次空检查就可以解决这个问题。我在上一条评论中所说的是,当您尝试将视图 (v) 转换为 ImageView 时,可能会遇到类型转换异常...
    • 我明白你说的。但是,dragImage 不能为空。我添加了更多代码以提供更多上下文。
    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2012-10-19
    • 2016-08-04
    • 2016-09-20
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多