简体   繁体   English

从“自定义”视图调用活动方法

[英]Call Activity method from Custom view

How to call an activity method from custom view? 如何从自定义视图调用活动方法?

public class CustomView extends LinearLayout {

    private Context mContext;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attributes) {
        findViewById(R.id.textView).setOnClickListener(v -> ((MyActivity) mContext).onClick(v));
    }
}

This works fine as I know that View is generated from MyActivity . 因为我知道View是从MyActivity生成的, MyActivity这个工作正常。

Is there any way to know which activity has created this CustomView ? 有什么办法知道哪个活动创建了这个CustomView吗? Something like getActivity().onClick(v) getActivity().onClick(v)

Do what all existing widgets do: accept a callback. 执行所有现有小部件的操作:接受回调。 So: 所以:

Step #1: Define some sort of callback or listener interface. 步骤#1:定义某种回调或侦听器接口。

Step #2: Add set...() on the widget to accept an instance of that interface, holding onto it in a field 步骤#2:在小部件上添加set...()以接受该接口的实例,并保留在字段中

Step #3: Have the activity, fragment, or whatever call that set...() method 步骤#3:使用活动,片段或任何set...()方法的调用

Step #4: Have the view call the callback (if one was supplied) when the event occurs 步骤#4:事件发生时,让视图调用回调(如果提供了回调)

You can see this pattern implemented for things like setOnClickListener() . 您可以看到针对setOnClickListener()类的东西实现了此模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM