How to pass view reference to android custom view?

后端 未结 3 652
無奈伤痛
無奈伤痛 2020-12-30 00:14

I did as follows

1) Creating a styleable


    
         


        
3条回答
  •  长发绾君心
    2020-12-30 01:03

    I know this is an old question, but I thought I would add another way of doing this as I wanted to encapsulate everything into my custom view.

    Instead of calling from the outside, another way of getting a view higher up in the hierarchy, I've hooked into onAttachedToWindow() instead:

    public class MyCustomView extends LinearLayout {
        private int siblingResourceId;
        private View siblingView;
    
        public MyCustomView(Context context, AttributeSet a) {
            super(context, attributeSet);
            inflate(context, R.layout.main6, this);
            TextView textView = (TextView) findViewById(R.id.custom_text);
            TypedArray t = context.obtainStyledAttributes(a, R.styleable.Viewee);
            siblingResourceId = t.getResourceId(R.styleable.MyCustomView_siblingResourceId, NO_ID);
            t.recycle();
        }
    
        @Override
        public void onAttachedToWindow() {
            super.onAttachedToWindow();
            if (siblingResourceId != NO_ID) {
                siblingView = ((View) getParent()).findViewById(siblingResourceId);
            }
        }
    }
    

    onAttachedToWindow is called quite early, but apparently late enough for the whole view hierarchy to have settled. It works flawless for my needs at least and is a little bit more controlled and doesn't need interaction from outside to work ;-)

    EDIT: Kotlin code added

    class MyCustomView(context: Context, attributeSet: AttributeSet) : LinearLayout(context, attributeSet) {
        private val siblingResourceId: Int
        private lateinit var siblingView: View
    
        // All other constructors left out for brevity.
    
        init {
            inflate(context, R.layout.main6, this)
            val textView = findViewById(R.id.custom_text)
            val t = context.obtainStyledAttributes(a, R.styleable.Viewee)
            siblingResourceId = t.getResourceId(R.styleable.MyCustomView_siblingResourceId, NO_ID)
            t.recycle()
        }
    
        override fun onAttachedToWindow() {
            super.onAttachedToWindow()
            if (siblingResourceId != NO_ID) {
                siblingView = (parent as View).findViewById(siblingResourceId) 
            }
        }
    }
    

    Note: We assume that the parent of this custom View is a View itself.

提交回复
热议问题