android - 从自定义 View 调用 Activity 方法

标签 android

如何从自定义 View 调用 Activity 方法?

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

这工作正常,因为我知道 View 是从 MyActivity 生成的。

有什么方法可以知道哪个 Activity 创建了这个CustomView?类似 getActivity().onClick(v)

最佳答案

执行所有现有小部件所做的操作:接受回调。所以:

第 1 步:定义某种回调或监听器接口(interface)。

步骤 #2:在小部件上添加 set...() 以接受该接口(interface)的实例,并将其保留在字段中

第 3 步:让 Activity、 fragment 或任何调用 set...() 方法

第 4 步:让 View 在事件发生时调用回调(如果提供了回调)

您可以看到这种模式是针对 setOnClickListener() 等实现的。

关于android - 从自定义 View 调用 Activity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56326488/

相关文章:

android - 无法在 android 上使用 GPS 获取可能的位置?

android - 如何设置actionBar中logo左右的间距?

android - 在 GridView 中动态添加多个按钮

android - Activity 的缩略图表示

android - 不兼容的类型错误 Geocoder Google API

android - FragmentPagerAdapter getItem 位置错误

android - 在没有互联网的设备上通过 Firebase 隐藏 ProgressDialog

android - 交换机错误代码

java - XML声明中的以下 "version"必须是带引号的字符串

Android WebView HTML5 Video Spawns MediaPlayer 永远存在于 Samsung S4 [找到黑客答案]