我是一名Android编程新手,试图将一个正在运行的应用从“活动”转移到“片段”。
在ScanningFragment(应显示附近的蓝牙设备列表)中,我输入了以下代码:
public class ScanningFragment extends ListFragment {
private ScanningListener mListener;
static class Beacon {
public String address;
public int rssi;
}
static class ViewHolder {
public ImageView image1;
public CheckedTextView text1;
}
private ArrayList<Beacon> mBeacons = new ArrayList<Beacon>();
private ArrayAdapter<Beacon> mAdapter;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_scanning, container, false);
mAdapter = new ArrayAdapter<Beacon>(getActivity(),
R.layout.rowlayout,
R.id.text1,
mBeacons) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.rowlayout, null);
holder = new ViewHolder();
holder.image1 = (ImageView) convertView.findViewById(R.id.image1);
holder.text1 = (CheckedTextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Beacon beacon = (Beacon) getItem(position);
holder.text1.setText(beacon.address);
// TODO pass selected address here
holder.text1.setChecked(beacon.address.equalsIgnoreCase(CommonConstants.ADDRESS_DEFAULT));
int res = CommonConstants.rssi2res(beacon.rssi);
holder.image1.setImageResource(res);
return convertView;
}
};
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Exception!
setListAdapter(mAdapter);
return view;
}
不幸的是行
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
使用IllegalStateException(此处为fullscreen)进行轰炸:
这是跟踪(这里是fullscreen,抱歉我不知道如何从Eclipse Debug窗口复制文本):
有人请知道,我在这里做错了什么?
答案 0 :(得分:1)
将该行移至onViewCreated()
而不是onCreateView()
。在onCreateView()
您的ListView
尚未创建,因此当您尝试检索它时会抛出IllegalStateException
。
另外,请确保activity_scanning.xml
包含ListView
android:id="@android:id/list"
。