我有一个TabLayout
,其中包含两个标签和一个MainActivity
。
如何将fragment1
中的数据发送到tab1
到MainActivity
}?
答案 0 :(得分:1)
您可以为此创建一个界面。请检查代码段。
片段
public class Fragment2 extends Fragment {
public interface onSomeEventListener {
public void someEvent(String s);
}
onSomeEventListener someEventListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
someEventListener = (onSomeEventListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
}
}
final String LOG_TAG = "myLogs";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, null);
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
someEventListener.someEvent("Test text to Fragment1");
}
});
return v;
}
}
活动
public class MainActivity extends Activity implements onSomeEventListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Fragment frag2 = new Fragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment2, frag2);
ft.commit();
}
@Override
public void someEvent(String s) {
Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
}
}
答案 1 :(得分:0)
如果您正在从片段调用活动并且想要将数据发送到Activity,则可以使用如下所示的意图:
Intent intent = new Intent(getActivity(), YourActivity.class);
String name = "Transporter";
intent.putExtra("name", name);
startActivity(intent);
在您的活动中,您应该获得如下数据:
try {
Intent intent = getIntent();
String name = intent.getStringExtra("name");
} catch(Exception e) {
e.printStackTrace();
}