对话框片段中的自定义ListView

时间:2016-10-07 17:13:48

标签: java xml listview android-studio android-dialogfragment

我已经在google上找了几个教程的解决方案,并在上传前检查了答案。

当我激活Dialog Fragment时,它显示为空。无论我做什么,它都不会加载我的ListView。

以下是我的代码:
对话片段代码:

public class MonthDialogFragment extends DialogFragment {
private Context context;

private String[] monthsArr = {"Jan", "Feb", "Mar", "Apr",
        "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    View view = LayoutInflater.from(context).inflate(R.layout.month_fragment_item, null);
    ListView listView = (ListView) view.findViewById(R.id.month_fragment_list_view);
    MonthItemAdapter adapter = new MonthItemAdapter(context, monthsArr);
    listView.setAdapter(adapter);
    builder.setView(view);
    return builder.create();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

这是列表适配器:

public class MonthItemAdapter extends ArrayAdapter{
private Context context;
private String[] months;
private TextView monthName;

public MonthItemAdapter (Context context, String[] months ){
    super(context, R.layout.month_list_item);
    this.context = context;
    this.months = months;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null){
        convertView = LayoutInflater.from(context).inflate(R.layout.month_list_item,null);
        monthName = (TextView) convertView.findViewById(R.id.month_list_item_text_view);
        convertView.setTag(monthName);
    }else{
        monthName = (TextView) convertView.getTag();
    }
    monthName.setText(months[position]);
    return convertView;
}

这就是我召唤对话片段的方式:

    @Override
public void onClick(View view) {
    if(view.getId() == etMonth.getId()) {
        monthFragment.show(getFragmentManager(), "");
    }
}

1 个答案:

答案 0 :(得分:0)

确保您实现了getCount()方法

@Override
    public int getCount() {
        return months.length;
    }