private void initTabView(LinearLayout layoutTab, BNRoutePlanItem bnRoutePlanItem) { TextView prefer = layoutTab.findViewById(R.id.prefer); prefer.setText(bnRoutePlanItem.getPusLabelName()); TextView time = layoutTab.findViewById(R.id.time); time.setText(getString(R.string.route_result_pass_time, (int) bnRoutePlanItem.getPassTime() / 60)); TextView distance = layoutTab.findViewById(R.id.distance); distance.setText(getString(R.string.route_result_distance_text, (int) bnRoutePlanItem.getLength() / 1000)); TextView trafficLight = layoutTab.findViewById(R.id.traffic_light); trafficLight.setText(String.valueOf(bnRoutePlanItem.getLights())); } 报错, java.lang.IllegalStateException: Fragment RouteResultFragment{f466a91} not attached to a context.
时间: 2024-03-17 08:45:44 浏览: 124
Android LinearLayout结合TextView选择列表项数据.rar
这个错误可能是因为您在Fragment中调用了与Context相关的方法,但Fragment未附加到Activity中,导致无法获得正确的Context。您可以尝试在onAttach()方法中保存Activity的Context并在需要时使用它。具体来说,您可以在Fragment中添加以下代码:
```
private Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
private void initTabView(LinearLayout layoutTab, BNRoutePlanItem bnRoutePlanItem) {
TextView prefer = layoutTab.findViewById(R.id.prefer);
prefer.setText(bnRoutePlanItem.getPusLabelName());
TextView time = layoutTab.findViewById(R.id.time);
time.setText(getString(R.string.route_result_pass_time, (int) bnRoutePlanItem.getPassTime() / 60));
TextView distance = layoutTab.findViewById(R.id.distance);
distance.setText(getString(R.string.route_result_distance_text, (int) bnRoutePlanItem.getLength() / 1000));
TextView trafficLight = layoutTab.findViewById(R.id.traffic_light);
trafficLight.setText(String.valueOf(bnRoutePlanItem.getLights()));
}
```
这样,您就可以在Fragment中使用Activity的Context了。
阅读全文