这是我的代码。其中有一个内部类名为 BirthDatePickerFragment
. 我想在全球范围内调用 birthYear
, birthMonth
, birthDay
变量形式 onCreateDialog
下的方法 BirthDatePickerFragment
.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button birthDatePickerButton;
TextView calculateTextView;
EditText birthDayDatePickerEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
birthDatePickerButton = findViewById(R.id.birthDatePickerBT);
birthDayDatePickerEditText = findViewById(R.id.birthDayDatePickEditTextID);
calculateTextView=findViewById(R.id.calculateTextViewID);
birthDatePickerButton.setOnClickListener(this);
}
public void onClick(View v) {
// Initialize a new date picker dialog fragment
DialogFragment dFragment = new BirthDatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
public static class BirthDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int birthYear = calendar.get(Calendar.YEAR);
int birthMonth = calendar.get(Calendar.MONTH);
int birthDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
AlertDialog.THEME_TRADITIONAL, this, birthYear, birthMonth,birthDay);
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Do something with the chosen date
EditText birthDatText=getActivity().findViewById(R.id.birthDayDatePickEditTextID);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date chosenDate = cal.getTime();
// Format the date using style short
DateFormat df_short = DateFormat.getDateInstance(DateFormat.SHORT);
String df_short_str = df_short.format(chosenDate);
// Display the formatted date
birthDatText.setText(df_short_str);
}
你可以把你的代码想得简单一些。如果你忽略外层类,只关注内部类,你会发现 onCreateDialog()
是类的一个公共方法 BirthDatePickerFragment
并返回一个 Dialog
对象。与所有在Java方法内部创建的变量一样,当方法结束时,它们会被清除。
如果你想获取 birthYear
, birthMonth
, birthDay
您必须通过以下方式访问它们。Dialog
方法返回的对象。这可能是可能的,因为变量是传递到对象的构造函数中的。
说了这么多,我同意评论中说的,你应该先想想你要做什么,看看是否可以根据你的目的改变代码的结构。