我认为由于片段,我需要使用getActivity()而不是这个。但它仍然会给出一个致命的错误并且不起作用。请帮助,提前谢谢......
public class TabFragment2 extends Fragment {
ListView listView;
String[] ids;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.tab_frag2_layout, container, false);
_audioModel.LoadModel();
listView = (ListView)V. findViewById(R.id.lsAudio);
String[] ids = new String[_audioModel.Audios.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
_audioAdapter adapter = new _audioAdapter(getActivity(),R.layout.audio_item, ids);
listView.setAdapter(adapter);
以下是我的_audioAdapter.java代码的一部分
public class _audioAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] Ids;
private final int rowResourceId;
public _audioAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.Ids = objects;
this.rowResourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
TextView audioName = (TextView) rowView.findViewById(R.id.textAudioName);
答案 0 :(得分:0)
我经常与这个问题斗争!! 问题在于片段/活动生命周期 在onCreateView中,如果片段是您活动的第一个,则活动尚不存在...... 如果您尝试调试或发布日志cat我认为错误是getActivity()上的NullPointerException
快速和肮脏的技巧:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/* All the code that need getActivity() */
}