从静态嵌套片段内的Activity访问变量

时间:2015-05-17 10:43:05

标签: android android-fragments

在我的活动中,我有一个TextView,我想从静态嵌套的DialogFragment设置文本。这是我的代码

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) {
        // Do something with the date chosen by the user
    }
}

3 个答案:

答案 0 :(得分:0)

public static MainActivity instance;

public MainActivity() {
    instance = this;
}


public void setText(final String text){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            textView.setText(text)
        }
    });
}

像这样使用

MainActivity.instance.setText("1234");

但我建议你远离静态实例,改为使用监听器(回调)!

答案 1 :(得分:0)

您不需要任何静态变量或任何可能导致内存泄漏的事情。您可以在活动上实现侦听器,并在片段附加时分配它。这是片段如何与其活动和其他片段进行通信的文档化方式。

public static class DatePickerFragment extends DialogFragment {
   private DatePickerDialog.OnDateSetListener mCallback;
   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);

       // This makes sure that the container activity has implemented
       // the callback interface. If not, it throws an exception
       try {
           mCallback = (DatePickerDialog.OnDateSetListener) activity;
       } catch (ClassCastException e) {
           throw new ClassCastException(activity.toString()
                   + " must implement 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(), mCallback, year, month, day);
    }
}

答案 2 :(得分:0)

解决我的问题:: 我刚在Activity中的textview变量之前添加了static modifier。