Java - Button onClick handler : Get focused view inside a view without having to click twice

268 views Asked by At

I suddenly encountered a strange behaviour. I create views completely dynamic. Basically I get data from db, which tells me how and what ui I should generate.

I get controls, like buttons, labels, whatever. Now I create two buttons dynamically, assign an own onClick handler with this logic

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

This is straight forward. The click is handled nice for the first button. The first control must top left receives the focus somehow by the runtime. But it is a strange focus. When I click on the other button, i have to click twice to process the event handler. And when I go back to the first button, I also have to click twice.

I found out, which line causes this behaviour.

    this.setClickable(true);        
    this.setFocusable(true);            
    this.setFocusableInTouchMode(true);  // <-- this line.

I remmed this line for test purposes. I now have another problem. I cannot get the focused control afterwards. But I need the name of the focused control. What can I do now ? Will I have to create an attribute in my fragmentactivity of type View, which I will fill in the onClickListener ? Or is there an internal mechanism ? I surely must not use setFocusableInTouchMode(true), because the user will have to click twice. requestFocus() does not help, because onClick handler is processed AFTER the button was clicked ONCE. What can I do best in this case ?

I now experimented with the OnTouchEvent in order to get this solved. And it works. However, I do not know, if this is the right approach, or the best preactice. Is there no better way "straight forward" in order to use the simple onClick handler to recieve the focus of the clicked button AND process the onClick event handler in ONE single way ?

0

There are 0 answers