从视图拨打电话
我有一个应用程序,其中包含一个活动,该活动显示我创建的自定义视图(拨号盘)。自定义视图有拨号盘、用于显示输入号码的编辑文本和一个电话按钮,我想用它来拨打用户输入的号码。我正在尝试为该按钮编写侦听器。侦听器必须从编辑文本中获取号码并对其进行调用。
我找到了可用于发出调用的代码并将其放置在我的 Activity 中:
public void call(String number){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但是按钮的侦听器位于自定义 View 类内部。如何从 View 类中的按钮侦听器调用 Activity 内的 call() 方法?
***编辑**
看来有一种更简单的方法,我发现可以将这段代码插入到 View 类中:
public void call(String number){
Intent intent = new Intent(Intent.ACTION_CALL);
String dialNumber = "tel:";
dialNumber = dialNumber + number;
intent.setData(Uri.parse(dialNumber));
getContext().startActivity(intent);
}
从侦听器调用此方法进行调用。
I have an app consisting of an Activity that displays a custom View that I created (a dialpad). The custom View has dials, an edittext used to display the number entered and a phonebutton that I want to use to place a call to the number the user has entered. Im trying to write the listener for that button. The listener must take the number from the edittext and place a call to it.
Ive found code that can be used to place calls and placed it in my Activity:
public void call(String number){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the listener for the button is inside the custom View class. How can I call the call() method inside the Activity from the button listener in the View class?
***EDIT**
It seems there was an easier way of doing it, I found this code that I could insert into the View class:
public void call(String number){
Intent intent = new Intent(Intent.ACTION_CALL);
String dialNumber = "tel:";
dialNumber = dialNumber + number;
intent.setData(Uri.parse(dialNumber));
getContext().startActivity(intent);
}
Calling this method from the listener places the call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使您是通过 startActivity 执行操作,从视图中调用 Activity 也不是一个好主意。问题是您的视图应该可移植到您想要创建的任何活动。通过直接调用或 startActivity,您可以将其与单一用途耦合。除了在那里之外,您永远无法在任何地方重用它,而且使用 startActivity() 不会做您认为它会做的事情。
相反,我会创建一个接口并向您的视图添加一个方法,该方法允许 Activity 将自身注册为某人拨打号码的侦听器。例如:
Not a good idea to call activity from within your view even if you're doing it through startActivity. Problem is your View should be portable to any Activity you want to create. By making direct calls or startActivity you're coupling it to that single use. You'll never be able to reuse it anywhere but right there, plus using startActivity() isn't going to do what you think it will do.
Instead I'd create an interface and add a method to your view that allows the Activity to register itself as a listener for someone dialing a number. For example: