【问题标题】:How to uniquely identify a View如何唯一标识一个视图
【发布时间】:2013-11-29 09:37:22
【问题描述】:

我是 Java 和 android 编程的新手,如果我的英语不好,我很抱歉:D

我正在制作一个具有拖放功能的应用程序。我将 RelativeLayout 用于放置区域并使用生成的 ImageView 作为项目。

数据来自 ListView。当我将 ListView 项拖放到 relativeLayout 上时,它将创建一个 ImageView。但是如何将 ListView 项中的值“插入”到 ImageView 中,以便在将新项放在布局上时检查现有数据,从而无法删除来自 listview 的相同数据。

这是我在 ACTION_DROP 上的代码

ClipData.Item item = event.getClipData().getItemAt(0);// I can get the dropped Item data from this
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
final RelativeLayout root = (RelativeLayout)findViewById(R.id.relLay);
final ImageView img = new ImageView(getApplicationContext());
img.setMinimumWidth(32);
img.setMaxWidth(32);
img.setMinimumHeight(32);
img.setMaxHeight(32);
img.setBackgroundResource(R.drawable.marker2);
img.setX(x_cord);
img.setY(y_cord);
root.addView(img);

【问题讨论】:

    标签: android android-listview drag-and-drop android-linearlayout android-imageview


    【解决方案1】:

    为您创建的每个视图创建一个唯一 ID,以便区分。

    Object tag = ... // Create a unique `tag` object depending on the data that comes from `ListView`
    
    ImageView existingView = root.findViewWithTag(tag);
    if (existingView == null) { // Didn't exist
        ImageView newView = new ImageView(getApplicationContext());
        newView.setTag(ID);
        root.addView(newView);
    }
    

    【讨论】:

    • +1 ,但他可以只使用setTag() 方法并检查标签是否不存在于relativelayout的子列表视图中而不使用customImageView :)
    • 在您的编辑代码中,您应该从根 RelativeLayout ( root.findViewWithTag(tag) ) 中找到 existingView 以获得更好的性能,以便使 UI Thread 仅在根布局中搜索而不是整体上Activity布局。
    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多