Android - 如何将数据从主活动发送到加载的片段

时间:2014-12-31 17:14:49

标签: java android android-fragments implementation

我希望function放置在Fragments中的所有MainActivity之间保持不变。我不确定如何将数据传递给active Fragment,因为Fragment将不知道正在运行的函数。

我尝试在interface中创建MainActivity,并Fragment implement MainActivity.OnDataPass。但不确定如何在MainActivity中启动界面{}继续获取NullPointerException

在我的主要活动中:

public class Mainactivity extends FragmentActivity{
    OnDataPass dataPasser;
    BroadcastReceiver receiver;
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String str = intent.getStringExtra("data");
                dataPasser.onDataPass(str);
            }
        };
    }

    public interface OnDataPass {
        public void onDataPass(String data);
    }
}

在我的片段中

public class Storage extends Fragment implements Mainactivity.OnDataPass{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        mrootview = (ViewGroup) inflater.inflate(R.layout.storage, container, false);
        return mrootview;
    }

    @Override
    public void onDataPass(String data) {
        Log.v(TAG, data);

    }
}
我甚至在正确的轨道上还是有更好的方法将数据发送到片段?

1 个答案:

答案 0 :(得分:2)

你已经很远了:

public class Mainactivity extends FragmentActivity{
    OnDataPass dataPasser;

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //When you create your fragment, keep a reference of it in the dataPasser variable
        dataPasser = /* your storage fragment class or any other fragment that implements onDataPass*/
        ......
        receiver = new BroadcastReceiver() {
              @Override
               public void onReceive(Context context, Intent intent) {
                    String str = intent.getStringExtra("data");
                    dataPasser.onDataPass(str);
               }
        };
    }       


    public interface OnDataPass {
        public void onDataPass(String data);
    }
}