2015-05-17 104 views
-2

在我的活动中我有一个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 
    } 
} 

回答

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"); 

不过我劝你从静态实例远离,并使用监听器(回调),而不是!

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); 
    } 
} 
0

解决方案:: 我只是内部活动的TextView变量前加入static修饰符。