IT序号网

java之触摸监听器和改变 parent

mate10pro 2023年09月15日 程序员 4 0

我为我的英语道歉。我有个问题。 我使用监听器 LongClick 和 TouchListener。

在长按中—— View 被移除,父 View 被插入到另一个父 View 中。 触摸停止工作,因为父级已更改。

如何让 TouchListener 保持查看状态?

static boolean drag = false; 
static View parent; 
static OnLongClickListener olcl = new OnLongClickListener() { 
    @Override 
    public boolean onLongClick(View v) { 
 
        if(!drag) { 
            parent = (View) v.getParent(); 
            int[] loc = {0, 0}; 
            v.getLocationOnScreen(loc); 
            ((ViewGroup) parent).removeView(v); 
            Main.mainRelative.addView(v); 
 
            RelativeLayout.LayoutParams par = (LayoutParams) v.getLayoutParams(); 
            par.leftMargin = loc[0]; 
            par.topMargin = loc[1]; 
            v.setLayoutParams(par); 
 
            drag = true; 
            return true; 
        } 
        return false; 
    } 
}; 
 
static OnTouchListener otl = new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
 
        if(v.getParent() != null && v.getParent() == Main.mainRelative) { 
            //!!!!!!!!!!!!! 
            RelativeLayout.LayoutParams par = (LayoutParams) v.getLayoutParams(); 
            par.leftMargin = (int) (event.getRawX() - v.getWidth()/2); 
            par.topMargin = (int) (event.getRawY() - v.getHeight()/1.2); 
            v.setLayoutParams(par); 
 
            for(int y = 0; y < Main.radioGroupLeftMain.getChildCount(); y++) { 
                RadioButton rb = (RadioButton) ((ViewGroup) Main.radioGroupLeftMain.getChildAt(y)).getChildAt(0); 
                if(checkHit((int)event.getRawX(), (int)event.getRawY(), rb)) { 
                    rb.setChecked(true); 
                } else { 
                    rb.setChecked(false); 
                } 
 
                if(event.getAction() == MotionEvent.ACTION_UP) { 
 
 
                    try { ((ViewGroup) v.getParent()).removeView(v); } catch(Exception e) {}; 
                    if(v.getVisibility() == View.VISIBLE) { 
                        ((ViewGroup) parent).addView(v); 
                    } 
                    drag = false; 
                } 
            }    
        } 
 
 
 
        return false; 
    } 
}; 
 
public static boolean checkHit(int x, int y, View v) { 
    int[] loc = {0, 0}; 
    v.getLocationOnScreen(loc); 
    Rect rv = new Rect(loc[0], loc[1], loc[0]+v.getWidth(), loc[1]+v.getHeight()); 
 
 
    return rv.contains(x, y); 
} 

请您参考如下方法:

当你要添加 View 时 Main.mainRelative.addView(v);
在创建新 View 之前,使用此 View v 进行初始化,例如 View vv = v
然后再次设置触摸监听器 vv.setOnTouchLIstener(ot1);
试试这个它应该工作...


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java之如何通过付款找到利率