考虑一下:
MainActivity有TextView id = txtMain
;
Activity2有一个名为Fragment1
;
Fragment1有TextView id = txtFrag;
如何从片段中获取字符串,以便出现在MainActivity中? 我尝试使用Bundle但不会工作。
答案 0 :(得分:0)
这是使用Bundles的工作代码,您可以检查代码是否有错误或在此处发布以供审核。
MainActivity.java
String textViewText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle textBundle=getIntent().getExtras();
textViewText=textBundle.get("TextView").toString();
}
@Override
protected void onResume() { // used onResume because until this call activity is created completely
super.onResume();
TextView textViewWidget=(TextView) findViewById(R.id.textView);
textViewWidget.setText(textViewTexts);
}
Fragment1.java
TextView text;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.toolbar_fragment,
container, false);
Button newActivity=(Button) view.findViewById(R.id.new_activity_button);
newActivity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text=(TextView) view.findViewById(R.id.txtFrag);
Intent newActivityIntent=new Intent(getActivity(),Main2Activity.class);
newActivityIntent.putExtra("TextView",text.getText());
startActivity(newActivityIntent);
}
});
}