JennyToy
JennyToy

Reputation: 628

onClickListener set on Activity

I have a class SomeView that extends View and that is displayed in a class Controls that extends linear layout.

The linear layout is instantiated onCreate of an activity. I would like to call a method in the activity every time I click on this view SomeView. I have tried to set an onClickListener in the activity like this

     public class MainActivity extends AppCompatActivity implements
     SomeView.OnClickListener {

     private Controls menu;

     @Override
     protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       menu = new Controls(this);
       menu.getSomeView().setOnClickListener(this); 

       setContentView(menu);

     }

     @Override
     public void onClick(View view) { 
      System.out.println("Hello");
     } 
     }

The controls class looks like this

    public class Controls extends LinearLayout  {

     private  SomeView aview;

     public Controls(Context context) {
            super(context);

            this.setOrientation(LinearLayout.HORIZONTAL);

            aview = new SomeView(context);

            this.addView(aview, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
     }

public SomeView getSomeView() {
        return aview;
    }

}

and the SomeView class looks like this (it just draws an oval)

public class SomeView extends View {
 public SomeView(Context context) {

        super(context);
    }

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        RectF aRect = new RectF();
        aRect.left = getPaddingLeft();
        aRect.top = getPaddingTop();
        aRect.right = getWidth() - getPaddingRight();
        aRect.bottom = getHeight() - getPaddingBottom();

        Paint aPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        aPaint.setColor(Color.GREEN);

        canvas.drawOval(aRect, aPaint);

}
}

But I am missing something because clicks are not calling the onClick method. What else do I need to set up?

Upvotes: 2

Views: 1008

Answers (1)

Ahad
Ahad

Reputation: 674

it seems like you did only mistake in your MainActivity class, where you forgot to call the super method. Try doing this, hope it will work, since it works from here in my mobile.

Main Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    menu = new Controls(this);
    menu.getSomeView().setOnClickListener(this);

    setContentView(menu);

}

And in your callback method, instead using System.out.println(), use Log.d() as below:

 @Override
 public void onClick(View view) { 
    Log.d(TAG, "Hello");
 } 

and it is working from here, look at the image below as well.

enter image description here

Upvotes: 1

Related Questions