How to Create onClickListener in Drawable EditText

21 May 2022

Home » Blogs » Android » How to Create onClickListener in Drawable EditText

You can create the () function in various ways by adding a click functionality to the icon.

For example, if you click on the “add” icon, it will add value to the one displayed by the . And if you click on the “remove” icon, it will reduce its value.

drawable click

activity_main.xml

In the layout, create an by adding icons to the ” drawableStart ” and ” drawableEnd “.

TOP TUTORIALS:  24 Pinout Voltage at ATX Power Supply to the Motherboard

The complete code for activity_main.xml is as follows:




    


MainActivity

In MainActivity add “ OnTouchListener ” as follows

public class MainActivity extends AppCompatActivity {

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText myText = findViewById(R.id.editText1);
        myText.setOnTouchListener((view, motionEvent) -> {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (motionEvent.getRawX() >= (myText.getRight() - myText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    Toast.makeText(MainActivity.this, "You clicked on Add Button", Toast.LENGTH_LONG).show();
                    return true;
                }
                if (motionEvent.getRawX() >= myText.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width()) {
                    Toast.makeText(MainActivity.this, "You clicked on Remove Button", Toast.LENGTH_LONG).show();
                    return true;
                }
            }
            return false;
        });
    }
}

0 Comments

Submit a Comment