从 custum imageview 调用方法

call method from custum imageview

我有一个 activity,它有一个自定义 imageView。在 imageView 中,我想从 activity.

中调用一个方法

这可能吗?

主要活动:

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();
       }

 }

换句话说,我想从 onDraw()(在 MyImageView 中)调用 myFunction(in Activity)

可以吗??

您可以使用上下文初始化图像,使用 MainActivity 的上下文(传递 MainActivity 的上下文)并在自定义图像视图中 class 声明上下文并使用传递的上下文进行初始化。当您在 MainActivity 中调用 public 方法时,请使用该上下文,就像我在下面所做的那样

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();
       }

 }