I have some problems to pass data from my activity to my fragment with the method onBackPressed() My activity
public class SingleArticle extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
On my fragment I have this
public class Home extends Fragment {
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("RETURN", "test = " );
}
}
The problem is that I can not see the log ... Do you have any idee how to resolve this ? Thank you
Use below code to pass data to fragment
Intent intent = new Intent(Context,fragment_class_name.class);
intent.putExtra(key, Value);
startActivity(intent);
//Pass the data from Activity to Fragment
Fragment newFragment=new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("item_id",1);
bundle.putString("item_data","description goes here");
newFragment.setArguments(bundle);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,newFragment, "newFragmentTag");
ft.commit();
//retrieve the data inside fragment
Bundle bundle = this.getArguments();
int id = bundle.getInt("item_id", 0);
String data = bundle.getString("item_data");
Here is one way to pass data from an Activity to a Fragment:
Create a static newInstance() method in the Fragment class:
public static MyFragment newInstance(String valueToPass) {
MyFragment instance = new MyFragment();
Bundle args = new Bundle();
args.putString("key", valueToPass);
instance.setArguments(args)
return instance;
}
Pass the data from the Activity/Fragment to MyFragment like so:
MyFragment myFragment = MyFragment.newInstance("Hello World");
Then you can do this to retrieve the data (any time after Fragment.onCreate())
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
String passedValue = getArguments().getString("key");
// passedValue == "Hello World"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.