这是我的容器活动Table_info
,我想将容器活动中的数据传递给其子片段Table_no
。但我收到片段中的字符串null
。
Table_info的代码:
package com.example.androiddbconnection;
import android.content.Intent;
import android.os.Bundle;
android.support.v4.app.FragmentActivity;
import android.util.Log;
public class Table_info extends FragmentActivity {
String restaurant;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tableinfo_frag);
Intent in=getIntent();
Bundle bundle = getIntent().getExtras();
restaurant = bundle.getString("outletname");
Log.d("in mainactivity",restaurant);
Bundle bundle1 = new Bundle();
bundle1.putString("restaurant",restaurant);
Table_no fragment=new Table_no();
fragment.setArguments(bundle1);
}
}
这是我的片段 Table_no :
public class Table_no extends Fragment {
String restaurant12;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle=getArguments();
if (bundle == null) {
Toast.makeText(getActivity(),"argum is null", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getActivity(),"argume", Toast.LENGTH_LONG).show();
restaurant12=bundle.toString();
Log.d("arguments", restaurant12);
}
}
但我收到的回复是'argum is null'
答案 0 :(得分:1)
为了从活动中调用Fragment的方法,您需要将活动添加到FragmentTransaction
,那么您可以这样做:
:
Table_no mTable_no = (Table_no) getFragmentManager().findFragmentByTag("Table_no_tag");
mTable_no.setMyData(String);
片段网站上的:
public void setMyData(String string) {
this.string = string;
}
答案 1 :(得分:0)
对片段使用构造函数。你可以使用它的构造函数直接将值传递给fragment。
public class Table_no extends Fragment {
String restaurant12="";
public Table_no(String restaurant)
{
restaurant12=restaurant;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(),restaurant12, Toast.LENGTH_LONG).show();
}
答案 2 :(得分:0)
即使我面临同样的问题,但添加以下行解决了我的问题。
Bundle bundle = getIntent().getExtras();
String getFeatureDescription= bundle.getString("desc");
Bundle b = new Bundle();
fragmentManager = getSupportFragmentManager();
b.putString("bb",getFeatureDescription);
FragmentFeatureOverview ff = new FragmentFeatureOverview();
ff.setArguments(b );
fragmentManager.beginTransaction().replace(R.id.fragmentContainer,ff).commit();
但是在添加此行后,我的标签会停止交换。
fragmentManager.beginTransaction().replace (R.id.fragmentContainer,ff).commit();