get parent's view from a layout

后端 未结 7 2243
囚心锁ツ
囚心锁ツ 2020-12-25 09:54

I have a FragmentActivity with this layout:




        
相关标签:
7条回答
  • 2020-12-25 10:34

    The getParent method returns a ViewParent, not a View. You need to cast the first call to getParent() also:

    RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();
    

    As stated in the comments by the OP, this is causing a NPE. To debug, split this up into multiple parts:

    ViewParent parent = this.getParent();
    RelativeLayout r;
    if (parent == null) {
        Log.d("TEST", "this.getParent() is null");
    }
    else {
        if (parent instanceof ViewGroup) {
            ViewParent grandparent = ((ViewGroup) parent).getParent();
            if (grandparent == null) {
                Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
            }
            else {
                if (parent instanceof RelativeLayout) {
                    r = (RelativeLayout) grandparent;
                }
                else {
                    Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
                }
            }
        }
        else {
            Log.d("TEST", "this.getParent() is not a ViewGroup");
        }
    }
    
    //now r is set to the desired RelativeLayout.
    
    0 讨论(0)
提交回复
热议问题