这是我创建的TimePicker类的代码
picker.java
package com.example.abhijeet.todo;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
/**
* Created by Abhijeet on 9/6/2017.
*/
public class Picker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
//Creating a View object because this class do not extend from activity class so no findviewbyid() method is present
View v =View.inflate(* ? *,R.layout.activity_editor,null); //HERE
//Displaying the user selected time on the Edit Text view
EditText edittime = (EditText) v.findViewById(R.id.time_editext_field);
}
}
我试图在编辑文本框中显示通过选择器选择的时间。 我无法为争论找到合适的背景。
我已经阅读了答案here,它解释了上下文的不同用法,但这似乎对我没有帮助。
感谢Advance中的帮助。
答案 0 :(得分:0)
只需致电getContext()
由于DialogFragment是Fragment的孩子。因此,可以在DialogFragment中调用所有Fragment类方法。
喜欢这个
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
//Creating a View object because this class do not extend from activity class so no findviewbyid() method is present
View v =View.inflate(getContext() ,R.layout.activity_editor,null); //HERE
//Displaying the user selected time on the Edit Text view
EditText edittime = (EditText) v.findViewById(R.id.time_editext_field);
}
您也可以调用getActivity()方法。如果您要定位到比23更旧的API:
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
//Creating a View object because this class do not extend from activity class so no findviewbyid() method is present
View v =View.inflate(getActivity() ,R.layout.activity_editor,null); //HERE
//Displaying the user selected time on the Edit Text view
EditText edittime = (EditText) v.findViewById(R.id.time_editext_field);
}
答案 1 :(得分:0)
无论何时使用。 Activity
- > getApplicationContext()
,Fragment
- > getActivity()
,Adapter
- > getContext()