自定义Android适配器从不显示数据

时间:2014-03-22 21:39:24

标签: java android listview

我已经编写了一个自定义的android适配器,当添加到ListFragment时它根本没有显示任何内容。我知道List<Alarm>中有值,数据库端正常工作。这是我的自定义适配器

public class AlarmListAdapter extends ArrayAdapter<Alarm>{

public AlarmListAdapter(Context context, int resource, List<Alarm> alarms) {
    super(context, resource);
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    if(view == null){
        LayoutInflater viewInflator = LayoutInflater.from(getContext());
        view = viewInflator.inflate(R.layout.item_alarm_list, null);
    }else{
        Alarm alarm = getItem(position);
        if(alarm != null){
            TextView alarmName = (TextView) view.findViewById(R.id.alarm_list_item_name);
            TextView alarmTime = (TextView) view.findViewById(R.id.alarm_list_item_time);
            Switch status = (Switch) view.findViewById(R.id.alarm_list_item_status);
            alarmName.setText(alarm.getName());
            alarmTime.setText(alarm.getHour() + ":" + alarm.getMinute());
            //TODO set the status of the alarms
            status.setChecked(true);
        }
    }
    return view;
}   

}

以下是我如何将适配器添加到ListFragment

List<Alarm> alarms = db.getAlarms();
AlarmListAdapter adapter = new AlarmListAdapter(getActivity(),
     R.layout.item_alarm_list, alarms);

布局R.layout.item_alarm_list如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<Switch
    android:id="@+id/alarm_list_item_status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/alarm_list_item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>

<TextView
    android:id="@+id/alarm_list_item_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>

我是Android的新手,我希望你的家伙可以帮助我理解这里发生的事情。提前谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

@Override
public View getView(int position, View view, ViewGroup parent) {
    if (view == null) {
        LayoutInflater viewInflator = LayoutInflater.from(getContext());
        view = viewInflator.inflate(R.layout.item_alarm_list, null);
    }
    Alarm alarm = getItem(position);
    if (alarm != null) {
        TextView alarmName = (TextView) view.findViewById(R.id.alarm_list_item_name);
        TextView alarmTime = (TextView) view.findViewById(R.id.alarm_list_item_time);
        Switch status = (Switch) view.findViewById(R.id.alarm_list_item_status);
        alarmName.setText(alarm.getName());
        alarmTime.setText(alarm.getHour() + ":" + alarm.getMinute());
        //TODO set the status of the alarms
        status.setChecked(true);
        return view;
    }
}

答案 1 :(得分:2)

我意识到我没有在super()调用中调用正确的构造函数。它应该是

super(context, resource, alarms);