关于将数据活动传递给Fragment有很多问题。
但我有“替换”方法的问题。我使用片段是因为滑动tablayout。
我想从Character1_activity.java传递数据 - > TabFragment1.java
这是代码。
Character1_Activity.java
public class Character1_Activity extends Activity implements View.OnClickListener{
public String food_box;
public String water_box;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
layoutParams.dimAmount = 0.7f; // 흐린 정도
getWindow().setAttributes(layoutParams);
setContentView(R.layout.character1);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.closebutton1 :
Intent intent = new Intent(this, Next_day.class);
CheckBox food = (CheckBox) findViewById(R.id.food_cb);
CheckBox water = (CheckBox) findViewById(R.id.water_cb);
if(food.isChecked() == true)
food_box = "true";
else
food_box = "false";
if(water.isChecked() == true)
water_box = "true";
else
water_box = "false";
TabFragment1 fragment = new TabFragment1();
if(fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("food_box", food_box);
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.game_main, fragment).addToBackStack(null).commit();
}
this.finish();
break;
这是TabFragment1
public class TabFragment1 extends Fragment {
String ch1_water;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container,false);
getArguments().getString("water_box");
}
答案 0 :(得分:2)
来自活动: -
Bundle bundle = new Bundle();
bundle.putString("food_box", foodbox);
fragment.setArguments(bundle);
片段onCreateView方法:
String strtext = getArguments().getString("food_box");
答案 1 :(得分:0)
(考虑到你不想使用bundle来传递数据)你可以尝试通过创建一个普通的单例类来在Activity和fragment之间传递数据。根据您的要求,您可以创建一个类来设置和获取数据。下面是单例类的一个示例,可用于在片段之间传递数据
public class DataClass {
private static DataClass dataObject = null;
private DataClass() {
}
public static DataClass getInstance() {
if (dataObject == null)
dataObject = new DataClass();
return dataObject;
}
private String distributor_id;;
public String getDistributor_id() {
return distributor_id;
}
public void setDistributor_id(String distributor_id) {
this.distributor_id = distributor_id;
}
}
设置数据
DataHolderClass.getInstance().setDistributor_id("your data");
并获取数据
String data = DataClass.getInstance().getDistributor_id();