How to pass view reference to android custom view?

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

I did as follows

1) Creating a styleable


    
         


        
3条回答
  •  北海茫月
    2020-12-30 00:51

    I found the answer!

    The issue was with findViewById(id) and where I called it. findViewById only looks for a child view not a view exist on upper hierarchy level as documentation says . So I have to call something like getRootView().findViewById(id) but that also returns null becase where I called it was not corrent.

    In Viewee constractor Viewee itself has not attached to its root yet so that call causes NullPointerException.

    So If I call to getRootView().findViewById(id) somewhere else after constraction, it works fine and both "@+id/tvTest" and "@id/tvTest" are correct. I've tested it!

    the answer is as follows

    public class Viewee extends LinearLayout
    {
        public Viewee(Context context, AttributeSet a)
        {
            super(context, attributeSet);
            View.inflate(context, R.layout.main6, this);
            TextView textView = (TextView) findViewById(R.id.custom_text);
            TypedArray t = context.obtainStyledAttributes(a, R.styleable.Viewee);
            int id = t.getResourceId(R.styleable.Viewee_linkedView, 0);
            if (id != 0)
            {
                _id = id;
            }
    
            t.recycle();
        }
    
        private int _id;
    
        public void Foo()
        {
            TextView textView = (TextView) findViewById(R.id.custom_text);
            View view = getRootView().findViewById(_id);
            textView.setText(((TextView) view).getText().toString());
        }
    }
    

    and Foo is called when it is required to process the attached view via its reference id somewhere else in your activity and the like.

    The credit completely goes to those guys contributed in this post. I had not seen that post before submitting the question.

提交回复
热议问题