Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button clicked", Toast.LENGTH_SHORT).show(); } });
public class CustomView extends View { private int mBackgroundColor = Color.WHITE; public CustomView(Context context) { super(context); init(); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBackgroundColor = Color.RED; invalidate(); } }); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(mBackgroundColor); } }Note: The package library for this class is android.view, but the CustomView class itself would be in a different package, depending on how it is organized in your project.