我正在学习使用Pickers而我无法将View传递给DatePickerFragment。这是一个示例完整项目源文件的github链接:https://github.com/MienTommy/DatePickerFragment
这是实现DatePickerFragment
的源代码package com.mienapps.datepickerfragment;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<TextView>
{
Activity mContext;
public CustomAdapter(Activity context, List<TextView> views)
{
super(context, 0, views);
mContext = context;
}
/*Get view from adapter*/
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View itemView = convertView;
if (convertView == null)
{
itemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
TextView datePickerView = (TextView) itemView.findViewById(R.id.date_picker);
datePickerView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(mContext.getFragmentManager(), "datePicker");
}
});
return itemView;
}
/*Time Picker*/
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
//TODO: set itemView to the date that is picked. However I can't access it from here.
}
}
}
在TODO部分,我想访问itemView,这样我就可以将文本设置为用户选择的日期。我不能使用findViewById来引用TextView,因为我的TextView是ListView的一部分。
答案 0 :(得分:0)
您可以在DatePickerFragment上添加一个接口并在您的适配器类中实现该接口,每当DatePickerFragment更新日期时,您都可以调用该接口。在适配器类中,您可以覆盖接口以执行任何操作。如果您是接口新手,可以在此处查看示例http://www.tutorialspoint.com/java/java_interfaces.htm
您可以将DatePickerFragment中的更新值存储在数据库中,在显示列表时,您可以从数据库中读取值。