【问题标题】:call method from custum imageview从 custum imageview 调用方法
【发布时间】:2019-04-27 23:39:36
【问题描述】:

我有一个具有自定义 imageView 的活动。在 imageView 中,我想从 Activity 中调用一个方法。

这可能吗?

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

 }

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

有可能吗?

【问题讨论】:

  • 你需要使用一个接口:stackoverflow.com/questions/994840/…
  • 是的,你可以打电话,但方法不对。将其设为静态方法并按类调用这些方法。
  • 为什么接口是错误的方法?

标签: android imageview


【解决方案1】:

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

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

 }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 2020-02-21
  • 2021-12-27
  • 2013-09-16
相关资源
最近更新 更多