0

I have an activity which has a custom imageView. In imageView, I want to call a method from the activity.

Is this possible?

MainActivity:

package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   int score=0;
   public void myFunction(){
       Log.d("LOG","call from imageView " + (score++));
   }

}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="This is a TextView" />

   <com.example.MyImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
       />
</LinearLayout>

MyImageViewClass

public class MyImageViewClass extends ImageView {

     public MyImageViewClass(Context context, AttributeSet attrs) {
          super(context, attrs);
      }

      protected void onDraw(Canvas canvas) {
            MainActivity.myFunction();
       }

 }

In other words, I want call myFunction(in Activity) from onDraw() (in MyImageView)

Is it possible??

Monolith
  • 1,067
  • 1
  • 13
  • 29
H Jahan
  • 11
  • 4

1 Answers1

1

You can work using the context initialize image using MainActivity's context (Pass MainActivity's context) and in custom imageview class declare context and initialize with the one passed. When you call a public method inside MainActivity use that context just like I have done below

public class MyImageViewClass extends ImageView {

     Context context;
     public MyImageViewClass(Context context, AttributeSet attrs) {
          super(context, attrs);
        this.context = context;
      }

      protected void onDraw(Canvas canvas) {
            ((MainActivity)context).myFunction();
       }

 }
Abid Khan
  • 2,451
  • 4
  • 22
  • 45
  • please answre this question https://stackoverflow.com/questions/55315028/settext-textview-from-custum-imageview – H Jahan Mar 23 '19 at 15:22