我想从listView上的Click方法中打开新的Activity。我为我的适配器实现单独的文件,并尝试从click listener方法打开新的Activity。但是当我尝试打开此活动时,它会显示我的错误。错误表明在线上有一个错误,我称之为:
((Activity) getContext()).startActivityForResult(intentBlock, position);
致命的例外:主要 过程:esticrm.pl.esticall,PID:28410 java.lang.IllegalStateException:片段CallsFragment {7b054bc}未附加到Activity 在android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1026) 在android.support.v4.app.Fragment.startActivityForResult(Fragment.java:1017) 在esticrm.pl.esticall.CallListAdapter $ 3.onClick(CallListAdapter.java:137) 在android.view.View.performClick(View.java:6199) 在android.view.View $ PerformClick.run(View.java:23647) 在android.os.Handler.handleCallback(Handler.java:751) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:154) 在android.app.ActivityThread.main(ActivityThread.java:6682) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1520) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
我设置onClickListener的适配器文件
public class CallListAdapter extends ArrayAdapter<CallList> {
public CallListAdapter(Context context, ArrayList<CallList> calls) {
super(context, 0, calls);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
CallList callList = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.call_list, parent, false);
}
block.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentBlock = new Intent(view.getContext(), BlockCallActivity.class);
intentBlock.putExtra("number", num);
intentBlock.putExtra("authToken", authToken);
((Activity) getContext()).startActivityForResult(intentBlock, position);
}
});
}
}
答案 0 :(得分:2)
将活动作为参数发布并调用activity.startActivity()
使用以下代码
public class CallListAdapter extends ArrayAdapter<CallList> {
Activity activity;
public CallListAdapter(Context context, ArrayList<CallList> calls,Activity activity) {
super(context, 0, calls);
this.activity = activity;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
CallList callList = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.call_list, parent, false);
}
block.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentBlock = new Intent(view.getContext(), BlockCallActivity.class);
intentBlock.putExtra("number", num);
intentBlock.putExtra("authToken", authToken);
activity.startActivityForResult(intentBlock, position);
}
});
}
}