传递参数/参数OnClickListener() [英] Passing arguments/parameters to OnClickListener()

查看:997
本文介绍了传递参数/参数OnClickListener()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和我仍然试图环绕其中一些概念我的头,所以我很抱歉,如果我要问频繁澄清。

我试图重写/创建自己的 OnClickListener 。不过,我得到这个错误,指出 startActivity(意向)是未定义我的课......我想不通为什么我收到此错误。

 进口android.content.ActivityNotFoundException;
进口android.content.Intent;
进口android.net.Uri;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;公共类ContactOCL实现OnClickListener {
    串CONTACTINFO;
    公共ContactOCL(字符串CONTACTINFO){
        this.contactInfo = CONTACTINFO;
    }    公共无效的onClick(视图v){
        尝试{
            意图callIntent =新意图(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse(电话:+ CONTACTINFO));
            startActivity(callIntent); //这里的错误
        }赶上(ActivityNotFoundException activityException){
            Log.e(拨打电话号码,呼叫失败,activityException);
        }
    }}


解决方案

既然你已经有一个查看传递给的onClick(),没有必要的活动也传递给封闭类。只要做到:

  v.getContext()startActivity(callIntent)。

I'm new to Android and I'm still trying to wrap my head around some of these concepts, so I'm sorry if I have to ask for frequent clarification.

I'm trying to override/create my own OnClickListener. However, I'm getting this error saying that startActivity(Intent) is undefined for my class...and I can't figure out why I'm getting this error.

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class ContactOCL implements OnClickListener {
    String contactInfo;
    public ContactOCL(String contactInfo) {
        this.contactInfo = contactInfo;
    }

    public void onClick(View v) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + contactInfo));
            startActivity(callIntent); // Error here
        } catch (ActivityNotFoundException activityException) {
            Log.e("Calling a Phone Number", "Call failed", activityException);
        }
    }

}

解决方案

Since you already have a View passed to onClick(), no need to also pass an Activity to the enclosing class. Just do:

v.getContext().startActivity(callIntent);

这篇关于传递参数/参数OnClickListener()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆