1

我在片段类中创建了一个类似于侦听器的接口,用于将字符串从片段发送到活动。向相反方向发送字符串的最佳方法是什么?从活动到碎片?所以现在片段中有一个接口,所以我必须在 Activity 中创建另一个接口以向另一个方向发送字符串,还是有更好的方法?

片段类:

 public class FragmentHeadless extends Activity implements FragmentHeadlessFragment.OnTimeRequestedListener {

FragmentTransaction transaction;
Button button;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_headless);

    button = (Button) findViewById(R.id.button1);
    textView = (TextView) findViewById(R.id.textView1);


    FragmentManager fragmentManager = getFragmentManager();
    transaction = fragmentManager.beginTransaction();

        transaction.add(new FragmentHeadlessFragment(), "processorFragment");
        transaction.commit();

}

@Override
public void passString(String stringFromFragment) {
     textView.setText(stringFromFragment);
     Toast.makeText(this, "String passed from fragment " + stringFromFragment, Toast.LENGTH_SHORT).show();

}

 }

活动课

 public class FragmentHeadlessFragment extends Fragment {

private OnTimeRequestedListener listener;
String tempString = "";
Activity activity;
Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    handler = new Handler();

    new Thread(){

        public void run() {

        SystemClock.sleep(3000);

        handler.post(new Runnable() {
            @Override
            public void run() {

                 // pass string to activity
              passData("test string from fragment with 3 second delay");


            }
         });

         } // end run

  }.start(); 

} // end onCreate

 @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);

    if (activity instanceof OnTimeRequestedListener) {
      listener = (OnTimeRequestedListener) activity;
    } else {
      throw new ClassCastException(activity.toString()
          + " must implemenet OnTimeRequestedListener");
    }
  }

@Override
 public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  activity = getActivity();
  setRetainInstance(true);


 }

 public interface OnTimeRequestedListener {
        public void passString(String timeNumberString);

  }

 public void passData(String data) {
        listener.passString(data);
    }



 }
4

1 回答 1

2

因为你有片段的实例,你可以通过活动调用你需要的函数:

代替 :

transaction.add(new FragmentHeadlessFragment(), "processorFragment");

利用:

private FragmentHeadlessFragment mFragment;
...
mFragment=new FragmentHeadlessFragment();
transaction.add(mFragment, "processorFragment");

如果您愿意,请致电:

mFragment.foo(myInt,myString,...) ;

顺便说一句,为什么你有一个交易字段?

于 2013-07-15T09:13:16.817 回答