我在我的自定义onClick
中设置TextView
到我的ListView
来电。点击TextView
后,我希望它能够打开Android的拨号屏幕。我将我的Activity的Context传递给了我的自定义适配器Java类,但每次点击TextView
时,应用程序仍然会崩溃。以下代码由构造函数以及我的自定义适配器Java类中的最后几个方法组成:
public CustomAdapter(Context c,ArrayList<String>n,ArrayList<String>nums, ArrayList<String>e){
context = c;
phoneNumbers = nums;
names = n;
emails = e;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
...
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
view = inflater.inflate(R.layout.contacts_custom_row,null);
TextView phone = (TextView)view.findViewById(R.id.customRowContactNumber);
phone.setOnClickListener(this);
}
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.customRowContactNumber:{
Intent i = new Intent(Intent.ACTION_DIAL);
context.startActivity(i);//I passed the context to my constructor
break;
}
}
}
请让我知道我做错了什么,谢谢。这是log cat错误:
09-21 17:48:49.451 2003-2003/com.markfeldman.mydoggydays E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.markf.dogdays, PID: 2003
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ContextImpl.startActivity(ContextImpl.java:1238)
at android.app.ContextImpl.startActivity(ContextImpl.java:1225)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
at com.markfeldman.mydoggydays.CustomAdapter.onClick(CustomAdapter.java:71)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
答案 0 :(得分:1)
如果你确定这里是你想要开始活动的地方,你可以添加
Intent i = new Intent(Intent.ACTION_DIAL);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
然后按原样启动它,
context.startActivity(i);
看起来你传递的上下文不是Activity的上下文,这就是为什么它会给你警告。如果您确定,可以通过更改类声明来执行@fixmycode建议的内容。
答案 1 :(得分:0)
在你的班级声明中:
public CustomAdapter(Activity activity, ...){
Activity myActivity = activity;
...
}
在你的onClick方法中:
myActivity.startActivity(...);