我想将一些活动的字符串数据发送到另一个活动的特定片段。就我而言,我有一个名为MainAcitivity的活动,用于发送数据和恢复活动,该活动在viewpager中有两个片段,名为AddNew.class。一个名为AddExpense的片段和第二个AddLedger。现在我想从AddExpense片段接收数据,而不是从AddLedger片段接收数据。我怎样才能做到这一点。 我点击了按钮,通过此代码发送数据
MainActivity
Intent intent = new Intent(MainActivity.this, AddNew.class);
intent.putExtra("edit_expense", "zohaib");
startActivity(intent);
接收活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Add Expense"));
tabLayout.addTab(tabLayout.newTab().setText("Add Ledger"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager2);
final TabAdapter adapter = new TabAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener (new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
片段,我想从中恢复数据,但我有两个片段,所以不想从其他片段接收数据。 收到片段:
public class AddExpenseFragment extends Fragment implements AdapterView.OnItemSelectedListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.add_expense, container, false);
AddNew activity = (AddNew) getActivity();
Utility.shortToast(getActivity(), activity.getIntent().getExtras().getString("edit_expense"));
return view;
}
上面代码中的问题,当AddNew acitivty创建了Toast时,会显示AddExpenseFragment是否已选中,但我不想这样做。我想仅从我想要接收的片段接收数据。请解决此问题。
答案 0 :(得分:0)
您应该在AddExpenseFragment中覆盖setUserVisibleHint
方法并将接收意图代码放入其中
答案 1 :(得分:0)
您可以在AddNew类中创建一个方法来接收意图数据,然后使用片段中的数据调用此方法
/* Method in AddNew Activity*/
private void yourIntentData()
{
return yourdata;
}
/* Method in AddExpenseFragment,type cast and call from the above parent class */
((AddExpenseFragment)getActivity).yourIntentData();