使用onBackPressed()方法将数据从我的活动传递到我的片段时遇到一些问题 我的活动
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();
}
}
在我的片段上我有这个
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 = " );
}
}
问题是我看不到日志...... 你有什么想法解决这个问题吗?谢谢
答案 0 :(得分:0)
使用以下代码将数据传递给片段
Intent intent = new Intent(Context,fragment_class_name.class);
intent.putExtra(key, Value);
startActivity(intent);
答案 1 :(得分:0)
//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");
答案 2 :(得分:0)
以下是将数据从活动传递到片段的一种方法:
在Fragment类中创建一个静态newInstance()方法:
public static MyFragment newInstance(String valueToPass) {
MyFragment instance = new MyFragment();
Bundle args = new Bundle();
args.putString("key", valueToPass);
instance.setArguments(args)
return instance;
}
将Activity / Fragment中的数据传递给MyFragment,如下所示:
MyFragment myFragment = MyFragment.newInstance("Hello World");
然后你可以这样做来检索数据(Fragment.onCreate()之后的任何时间)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
String passedValue = getArguments().getString("key");
// passedValue == "Hello World"
}
}