Search code examples
javaandroidbuttontextviewonclicklistener

Android - How to get the currently "focused" object?


I want to let a Button identify which of my TextViews got the current focus. And after that the Button needs to apply changes to the focused TextView.

    TextView textView11 = (TextView) findViewById(R.id.frame1_1);

    textView11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            textView11.setBackgroundColor(Color.LTGRAY);
            textView11.setFocusableInTouchMode(true);
            textView11.requestFocus();
        }
    });

    MaterialButton pb1 = (MaterialButton) findViewById(R.id.pin_button_1);
    pb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //1. get the focused textview or scan for the focused textView
            
            //2. apply button function to the focused textView

        }

    });

So how can i identify here

//1. get the focused textview or scan for the focused textView

which TextView has the focus currently? I think it might be possible with some help variable but maybe there os another way, because then i still need a onClickListener for each of the 22 TextView


Solution

  • Untested but should work

    private TextView hasFocusTextView;
    private View.OnFocusChangeListener onFocusChangedListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
                hasFocusTextView = (TextView) v;
        }
    };
    

    ..

    TextView textView11 = (TextView) findViewById(R.id.frame1_1);
    //Use same listener on all textview you want to include with the focus logic
    textView11.setOnFocusChangeListener(onFocusChangedListener); 
    
    pb1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hasFocusTextView.setText("Changing text of the focused TextView");
            }
    
    });