我希望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);
}
}
我甚至在正确的轨道上还是有更好的方法将数据发送到片段?
答案 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);
}
}