Android Studio Databinding: Can I access the contents of a binding within an onKey event?

371 Views Asked by At

I am trying to implement some button events without any reference to the XML-File and with databinding instead of FindByID. Is this possible? I am having the problem that, within the OnKeyListener, the bound InputBox from which I try to get the typed text seems inaccessible (this.binding shows in red color where I put it bold). Is this a wrong approach or am I making a mistake? I'd like to avoid all that FindByID-Lines.

this.binding =
            DataBindingUtil.setContentView(this, R.layout.content_main);
    this.binding.EditNumber.setText("553");

    this.binding.EditNumber.setOnKeyListener(new OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                switch (keyCode)
                {
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        Cat supertest = Manager.CreateMainCat(this.**binding**.EditNumber.toString());
                        this.**binding**.DisplayCurrentBudget.setText(supertest.getsName());
                        return true;
                    default:
                        break;
                }
            }
            return false;
        }
    });

Thank you very much

1

There are 1 best solutions below

0
On

Strangely, it works when I simply put the binding in another method:

    (...)
            this.binding.Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xxx();
            }
        });
    }

    public void xxx()
    {
        Cat supertest = Manager.CreateMainCat(this.binding.EditNumber.getText().toString());
        this.binding.DisplayCurrentBudget.setText(supertest.getsName());
    }

But this doesn't:

this.binding.Submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cat supertest = Manager.CreateMainCat(this.binding.EditNumber.getText().toString());
            this.binding.DisplayCurrentBudget.setText(supertest.getsName());
                }

The propblem is solved easily, but I'd be very interested to know what's going if someone has the answer :)