Android的:最好的方法来传递viewpager片段之间的数据 [英] Android: Best Approach to pass data between viewpager fragments
问题描述
我有一个ViewPager活动3片段。所有3片段具有输入字段。在这里,我想前两个片段数据传递给第三个片段。我在这里读几个岗位,其中大部分建议使用接口(即,通过家长的活动来传递数据)
我也通过这个链接了
http://developer.android.com/training/basics/fragments/communicating.html
接口:使用接口是,当我们通过一些用户事件发送数据好方法。在这里,我想没有任何用户事件发送数据。因此,我想的onPause(),因为在onPause()总是被调用的。但ViewPager功能各不相同。当被加载的片段,相邻的片段也装载。我会成功,以第一个片段之间的数据传递给第三个片段。但是第二片段的的onPause()不会被调用,除非我浏览到一些片段是不相邻的它(这在我的情况是不存在的)
二传手/吸气:我已阅读几篇文章的人说,不使用的setter / getter方法(我仍然还没有了解的原因还)的是否getter和setter方法设计不佳?
软件包:我还没有考虑过这个呢。由于我在这里再次弄得我将如何使用传送数据包(里面哪种方法,我应该发送的数据?又如何?)
如果我的问题听起来dumb.I想了解片段,我想知道通过在viewpager片段之间数据的最佳方式对不起。
谢谢你在前进。
TabPAgerAdapter - >
包com.jbandroid.model;进口com.jbandroid.fragment.LocationInfoFragment;
进口com.jbandroid.fragment.PersonalInfoFragment;
进口com.jbandroid.fragment.PostInfoFragment;进口android.support.v4.app.Fragment;
进口android.support.v4.app.FragmentManager;
进口android.support.v4.app.FragmentPagerAdapter;公共类TabsPagerAdapter扩展FragmentPagerAdapter { 公共TabsPagerAdapter(FragmentManager FM){
超(FM);
}
@覆盖
公共片段的getItem(INT指数){ 开关(指数){ 案件0:// PostInfoFragment
返回新PostInfoFragment(); 案例1:// LocationInfoFragment
返回新LocationInfoFragment(); 案例2:// PersonalInfoFragment
返回新PersonalInfoFragment(); } 返回null;
} @覆盖
公众诠释的getCount(){
//获取项目计数 - 等于标签数
返回3;
}}
ViewPagerActivity - >
包com.jbandroid;公共类SubmitPostActivity扩展FragmentActivity实现ActionBar.TabListener,PostInfoFragment.setPostInfo,LocationInfoFragment.setLocationInfo { 私人ViewPager viewpager;
私人动作条动作条;
私人TabsPagerAdapter mAdapter;
FragmentManager经理;
PersonalInfoFragment FRAG;
清单<串GT;位置;
/ *私人菜单项myActionMenuItem;
私人按钮myActionButton; * /
//标签标题
私有String []选项卡= {邮报信息,位置信息,个人信息}; @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.action_submit_post); viewpager =(ViewPager)findViewById(R.id.pager);
动作条= getActionBar();
经理= getSupportFragmentManager();
mAdapter =新TabsPagerAdapter(getSupportFragmentManager());
//viewpager.setOffscreenPageLimit(2);
viewpager.setAdapter(mAdapter); //actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 对于(字符串标签:标签){
actionBar.addTab(actionBar.newTab()的setText(标签).setTabListener(本));
} 如果(savedInstanceState!= NULL){
actionBar.setSelectedNavigationItem(savedInstanceState.getInt(标签,0));
} / **
*上刷卡viewpager做出选择相应的标签
* * / viewpager.setOnPageChangeListener(新OnPageChangeListener(){ @覆盖
公共无效使用onPageSelected(INT位置){
//上改变页面
//使受人尊敬的选项卡中选择
actionBar.setSelectedNavigationItem(位置);
} @覆盖
公共无效onPageScrolled(INT为arg0,ARG1浮球,诠释ARG2){ } @覆盖
公共无效onPageScrollStateChanged(INT为arg0){ }
});
} @覆盖
保护无效的onSaveInstanceState(捆绑outState){
super.onSaveInstanceState(outState);
outState.putInt(标签,getActionBar()getSelectedNavigationIndex());
} @覆盖
公共无效onTabReselected(标签选项卡,FragmentTransaction英尺){ } @覆盖
公共无效onTabSelected(标签选项卡,FragmentTransaction英尺){
//在选项卡中选择
//秀推崇片段视图 viewpager.setCurrentItem(tab.getPosition()); } @覆盖
公共无效onTabUnselected(标签选项卡,FragmentTransaction英尺){ } @覆盖
公共无效pass_location_details(列表<串GT;位置){ FRAG =(PersonalInfoFragment)manager.findFragmentByTag(机器人:切换:+ viewpager.getId()+:+ 2);
frag.get_post_location_details(位置);
Log.d(submitarea,location.get(0));
}
@覆盖
公共无效pass_post_details(列表<串GT; post_details,ArrayList的< CustomGallery>选择){
FRAG =(PersonalInfoFragment)manager.findFragmentByTag(机器人:切换:+ viewpager.getId()+:+ 2);
frag.get_post_details(post_details,选择);
Log.d(submitpostinfo,你好+ post_details.get(5));
}
}
1片段(在这里,我试图在使用的onPause接口数据传递() - >
包com.jbandroid.fragment;
公共类PostInfoFragment扩展片段{ 私人菜单项myActionMenuItem;
私人按钮myActionButton;
私人动作条动作条;
私人字符串POST_TITLE,post_desc,post_status; 私人的EditText submit_post_title,submit_post_desc; 私人资源资源; setPostInfo信息;
清单<串GT; post_details;
// RelativeLayout的rel_submit_post_start_date,rel_submit_post_end_date; @覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){
查看rootView = inflater.inflate(R.layout.fragment_post_info,
集装箱,FALSE); /*if(!imageLoader.isInited()){*/
initImageLoader();
/ *} * / //处理程序=新的处理程序();
submit_post_title =(EditText上)rootView
.findViewById(R.id.submit_post_title);
submit_post_desc =(EditText上)rootView
.findViewById(R.id.submit_post_description); 动作条= getActivity()getActionBar()。
setHasOptionsMenu(真); post_details =新的ArrayList<串GT;();
RES = getResources(); setListeners(); Log.d(postinfo_oncreate观,postinfo_oncreate视图); 返回rootView; } //接口将数据传递到活动,然后到PersonalInfoFragment
公共接口setPostInfo {
//公共无效pass_post_details(列表<串GT; post_details);
公共无效pass_post_details(列表<串GT; post_details,ArrayList的< CustomGallery>选择);
}
//确保当父活动已实现的接口
@覆盖
公共无效onAttach(活动活动){
super.onAttach(活动);
//这将确保集装箱活动实施
//回调接口。如果不是,它抛出一个异常
尝试{
信息=(setPostInfo)活性;
}赶上(抛出ClassCastException E){ 抛出新ClassCastException异常(activity.toString()
+必须implemet setPostInfo);
} Log.d(postinfo_onattach,postinfo_onattach);
}
//传递形式输入personalinfofragments
@覆盖
公共无效的onPause(){
super.onPause();
// setFormInputs(); passFormInputs(); --->传递的onPause()这个成功执行 Log.d(postinfo_onPAuse,postinfo_onPause); }
//方法将数据传递给personalinfofragment
私人无效passFormInputs(){
尝试{
。POST_TITLE = submit_post_title.getText()的toString();
post_desc = submit_post_desc.getText()的toString()。
post_status =1; 如果(POST_TITLE =空&放大器;!&放大器; post_title.length()大于0 &功放;&安培; post_desc = NULL&放大器;!&安培; post_desc.length()> 0
&功放;&安培; post_status = NULL&放大器;!&安培; post_status.length()> 0
){
post_details.add(POST_TITLE);
post_details.add(post_desc);
post_details.add(post_status); info.pass_post_details(post_details,dataT); - >此处我通过传递值
}其他{活动第三片段
Log.d(post_info,值均为空);
}
}赶上(例外五){
e.printStackTrace();
}
}
//设置在动作条下一个按钮
公共无效onCreateOptionsMenu(菜单菜单,MenuInflater气筒){
super.onCreateOptionsMenu(菜单,充气器); //充气操作栏中使用的菜单项 inflater.inflate(R.menu.mymenu,菜单); //这里我们得到我们定义的操作视图
myActionMenuItem = menu.findItem(R.id.my_action);
查看的actionView = myActionMenuItem.getActionView(); //我们再拿到按钮认为是动作视图的一部分
如果(的actionView!= NULL){
myActionButton =(按钮)actionView.findViewById(R.id.action_btn);
myActionButton.setText(R.string.txt_next);
如果(myActionButton!= NULL){
//我们设置一个侦听器时返回/输入将被调用
//关键是pressed
myActionButton.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){ actionBar.setSelectedNavigationItem(1);
}
});
}
} }}
第二片段 - >
包com.jbandroid.fragment;公共类LocationInfoFragment扩展片段实现OnClickListener { 私人菜单项myActionMenuItem;
私人按钮myActionButton;
私人动作条动作条; 对话的对话;
私人的EditText submit_post_exact_location;
私人TextView的selected_country,selected_city,
submit_post_exact_time;
字符串的国家,城市,exact_location,EXACT_TIME;
setLocationInfo信息; 清单<串GT;位置; @覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){ 查看rootView = inflater.inflate(R.layout.fragment_location_info,
集装箱,FALSE);
动作条= getActivity()getActionBar()。
setHasOptionsMenu(真);
submit_post_exact_location =(EditText上)rootView
.findViewById(R.id.submit_post_exact_location);
submit_post_exact_time =(TextView中)rootView
.findViewById(R.id.submit_post_exact_time); selected_country =(TextView中)rootView
.findViewById(R.id.selected_country);
selected_city =(TextView中)rootView.findViewById(R.id.selected_city); 位置=新的ArrayList<串GT;();
setListeners(); 返回rootView; } 公共无效onCreateOptionsMenu(菜单菜单,MenuInflater气筒){
super.onCreateOptionsMenu(菜单,充气器); //充气操作栏中使用的菜单项 inflater.inflate(R.menu.mymenu,菜单); //这里我们得到我们定义的操作视图
myActionMenuItem = menu.findItem(R.id.my_action);
查看的actionView = myActionMenuItem.getActionView(); //我们再拿到按钮认为是动作视图的一部分
如果(的actionView!= NULL){
myActionButton =(按钮)actionView.findViewById(R.id.action_btn);
myActionButton.setText(R.string.txt_next);
如果(myActionButton!= NULL){
//我们设置一个侦听器时返回/输入将被调用
//关键是pressed
myActionButton.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){
actionBar.setSelectedNavigationItem(2); }
});
}
}
}
公共接口setLocationInfo {
公共无效pass_location_details(列表<串GT;位置);
} @覆盖
公共无效onAttach(活动活动){
super.onAttach(活动);
//这将确保集装箱活动实施
//回调接口。如果不是,它抛出一个异常
尝试{
信息=(setLocationInfo)活性;
}赶上(抛出ClassCastException E){
抛出新ClassCastException异常(activity.toString()
+必须实现setLocationInfo);
}
} @覆盖
公共无效onActivityCreated(捆绑savedInstanceState){
super.onActivityCreated(savedInstanceState);
// setLocationDetails();
} @覆盖
公共无效的onPause(){
super.onPause();
setLocationDetails(); ---->犯规执行以来的onPause心不是叫,当我浏览到第3段,因为它是这个片段的附近片段
// Log.d(位置:在onPause,区);
} 私人无效setLocationDetails(){
尝试{ 。exact_location = submit_post_exact_location.getText()的toString();
。EXACT_TIME = submit_post_exact_time.getText()的toString();
国家= selected_country.getText()的toString()。
城市= selected_city.getText()的toString()。 如果(国家= NULL&放大器;!&安培; country.length()大于0
&功放;&安培; !country.equalsIgnoreCase(选择)及和放大器;城市!= NULL
&功放;&安培; city.length()> 0安培;&安培; !city.equalsIgnoreCase(选择) &功放;&安培; exact_location = NULL&放大器;!&安培; exact_location.length()> 0
&功放;&安培; EXACT_TIME = NULL&放大器;!&安培; exact_time.length()> 0){ location.add(国家);
location.add(市); location.add(exact_location);
location.add(EXACT_TIME);
info.pass_location_details(位置);
}
}赶上(例外五){
e.printStackTrace();
}
}
}
在我的第三个片段,我试图让这个值
公共类PersonalInfoFragment扩展片段{
清单<串GT; post_details;
清单<串GT;位置;
按钮提交;
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){
查看rootView = inflater.inflate(R.layout.fragment_personal_info,
集装箱,FALSE);
提交=(按钮)rootView.findViewById(R.id.submitBtn);
submit.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(视图v){ //执行操作以获得的值
setPostItems(); insertintodb();
}
}); 返回rootView;
} 公共无效get_post_details(列表<串GT; post_details,
ArrayList的< CustomGallery>选择){ - &购自接收值
this.post_details = post_details;第一个片段
this.selected =选择;
Log.d(personalfrag(postinfo),你好+ post_details.get(5));
}
//从第二个片段接收值
公共无效get_post_location_details(列表<串GT;位置){
this.location =位置;
Log.d(personalfrag(locationinfo),你好+ location.get(0));
}
}
好吧,我有同样的问题,通过在ViewPager两个选项卡之间的数据(不只是字符串)。因此,这里是我做过什么。
我使用的接口的不同组件之间进行通信。
数据通过这种方式:
设置页,第1 - >活动 - > VewPageAdapter - >表2
不是很多人会说,它的一个好办法,但... .. MEH它的工作原理:D
- 在标签1
创建一个接口。
OnCartsDataListener mOncarOnCartsDataListener;
公共接口OnCartsDataListener { 公共无效onCartsDataReceived(ArrayList的< CartsViewModel> cartsViewModels);}@覆盖
公共无效onAttach(活动活动){
super.onAttach(活动);
尝试{
mOncarOnCartsDataListener =(OnCartsDataListener)活性;
}赶上(抛出ClassCastException E){ }}
//现在称之为mOncarOnCartsDataListener.onCartsDataReceived(数据)时,你有数据
<醇开始=2>
实现接口和重写方法
ViewPagerAdapter适配器;
适配器=新ViewPagerAdapter(getSupportFragmentManager(),标题,Numboftabs);@覆盖
公共无效onCartsDataReceived(ArrayList的&LT; CartsViewModel&GT; cartsViewModels){
Log.d(TAG,数据接收到活动...发送到寻呼机查看);
adapter.onCartsDataReceived(cartsViewModels);
}
3 在ViewPagerAdapter
也实现了接口,并覆盖的方法
@覆盖
公共无效onCartsDataReceived(ArrayList的&LT; CartsViewModel&GT; cartsViewModels){
Log.d(TAG,接收到的数据,查看传呼机...发送给标签2); 如果(TAB2!= NULL){
tab2.onCartsDataReceived(cartsViewModels);
}其他{
Log.d(TAG,TAB2为空);
}
}
<醇开始=4>
也实现了接口,并覆盖的方法
@覆盖
公共无效onCartsDataReceived(ArrayList的&LT; CartsViewModel&GT; cartsViewModels){
Log.d(TAG!最后接收到的数据标签2);
如果(cartsViewModels!= NULL){
对于(CartsViewModel购物车:cartsViewModels){
Log.d(TAG,得到了它:+ cart.getCartName());
}
}
}
I have 3 fragments in a ViewPager Activity. All 3 fragments have input fields. Here I am trying to pass first two fragments data to third fragment. I read few posts here and most of them suggested to use interfaces(i.e. to pass data through parent activity) I have also gone through this link http://developer.android.com/training/basics/fragments/communicating.html
Interface: using interfaces is good approach when we are sending data through some user event. Here I am trying to send data without any user event. Hence I thought of onPause() since onPause() is always called. But ViewPager functions differently. When a fragment is loaded,the adjacent fragments are also loaded. I would be successful to pass data between 1st fragment to 3rd fragment. But 2nd fragment's onPause() wont be called unless I am navigating to some fragment that is not adjacent to it(which in my case is not there)
Setter/Getters:I have read in few posts people saying not to use setter/getters(I still havent understood the reason yet) Are getters and setters poor design?
Bundle: I havent considered this yet. Since I am again confused here how would I pass data using bundle.(inside which method should I send data? and how?)
Sorry if my question sounds dumb.I am trying to understand fragments and i would like to know best way to pass data between fragments in viewpager. Thank You in advance.
TabPAgerAdapter -- >
package com.jbandroid.model;
import com.jbandroid.fragment.LocationInfoFragment;
import com.jbandroid.fragment.PersonalInfoFragment;
import com.jbandroid.fragment.PostInfoFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int index) {
switch(index) {
case 0 : //PostInfoFragment
return new PostInfoFragment();
case 1 : //LocationInfoFragment
return new LocationInfoFragment();
case 2 : //PersonalInfoFragment
return new PersonalInfoFragment();
}
return null;
}
@Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
ViewPagerActivity -- >
package com.jbandroid;
public class SubmitPostActivity extends FragmentActivity implements ActionBar.TabListener,PostInfoFragment.setPostInfo,LocationInfoFragment.setLocationInfo{
private ViewPager viewpager;
private ActionBar actionBar;
private TabsPagerAdapter mAdapter;
FragmentManager manager;
PersonalInfoFragment frag;
List<String> location;
/*private MenuItem myActionMenuItem;
private Button myActionButton;*/
//Tab titles
private String[] tabs = {"Post Info" , "Location Info" , "Personal Info" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_submit_post);
viewpager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
manager = getSupportFragmentManager();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
//viewpager.setOffscreenPageLimit(2);
viewpager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab : tabs){
actionBar.addTab(actionBar.newTab().setText(tab).setTabListener(this));
}
if(savedInstanceState != null){
actionBar.setSelectedNavigationItem( savedInstanceState.getInt("tab",0));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewpager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void pass_location_details(List<String> location) {
frag = (PersonalInfoFragment) manager.findFragmentByTag("android:switcher:" + viewpager.getId() + ":" + 2);
frag.get_post_location_details(location);
Log.d("submitarea", location.get(0));
}
@Override
public void pass_post_details(List<String> post_details,ArrayList<CustomGallery> selected) {
frag = (PersonalInfoFragment) manager.findFragmentByTag("android:switcher:" + viewpager.getId() + ":" + 2);
frag.get_post_details(post_details,selected);
Log.d("submitpostinfo","hello"+ post_details.get(5));
}
}
1st Fragment(Here I am trying to pass data using interface in onPause()-->
package com.jbandroid.fragment;
public class PostInfoFragment extends Fragment {
private MenuItem myActionMenuItem;
private Button myActionButton;
private ActionBar actionBar;
private String post_title, post_desc,post_status;
private EditText submit_post_title, submit_post_desc;
private Resources res;
setPostInfo info;
List<String> post_details;
//RelativeLayout rel_submit_post_start_date,rel_submit_post_end_date;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_post_info,
container, false);
/*if(!imageLoader.isInited()){*/
initImageLoader();
/*}*/
//handler = new Handler();
submit_post_title = (EditText) rootView
.findViewById(R.id.submit_post_title);
submit_post_desc = (EditText) rootView
.findViewById(R.id.submit_post_description);
actionBar = getActivity().getActionBar();
setHasOptionsMenu(true);
post_details = new ArrayList<String>();
res = getResources();
setListeners();
Log.d("postinfo_oncreate view", "postinfo_oncreate view");
return rootView;
}
//interface to pass data to activity and then to PersonalInfoFragment
public interface setPostInfo {
//public void pass_post_details(List<String> post_details);
public void pass_post_details(List<String> post_details,ArrayList<CustomGallery> selected);
}
//making sure if the parent activity has implemented interface
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
info = (setPostInfo) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ "must implemet setPostInfo");
}
Log.d("postinfo_onattach", "postinfo_onattach");
}
//passing form inputs to personalinfofragments
@Override
public void onPause() {
super.onPause();
// setFormInputs();
passFormInputs(); ---> passing in onPause() This executes successfully
Log.d("postinfo_onPAuse", "postinfo_onPause");
}
//method to pass data to personalinfofragment
private void passFormInputs() {
try {
post_title = submit_post_title.getText().toString();
post_desc = submit_post_desc.getText().toString();
post_status = "1";
if(post_title != null && post_title.length() > 0
&& post_desc != null && post_desc.length() > 0
&& post_status != null && post_status.length() > 0
){
post_details.add(post_title);
post_details.add(post_desc);
post_details.add(post_status);
info.pass_post_details(post_details,dataT); -->here I am passing values via
}else{ activity to 3rd fragment
Log.d("post_info", "values are null");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//setting next button on actionbar
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu items for use in the action bar
inflater.inflate(R.menu.mymenu, menu);
// Here we get the action view we defined
myActionMenuItem = menu.findItem(R.id.my_action);
View actionView = myActionMenuItem.getActionView();
// We then get the button view that is part of the action view
if (actionView != null) {
myActionButton = (Button) actionView.findViewById(R.id.action_btn);
myActionButton.setText(R.string.txt_next);
if (myActionButton != null) {
// We set a listener that will be called when the return/enter
// key is pressed
myActionButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
actionBar.setSelectedNavigationItem(1);
}
});
}
}
}
}
2nd Fragment-->
package com.jbandroid.fragment;
public class LocationInfoFragment extends Fragment implements OnClickListener {
private MenuItem myActionMenuItem;
private Button myActionButton;
private ActionBar actionBar;
Dialog dialog;
private EditText submit_post_exact_location;
private TextView selected_country, selected_city,
submit_post_exact_time;
String country, city, exact_location, exact_time;
setLocationInfo info;
List<String> location;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_location_info,
container, false);
actionBar = getActivity().getActionBar();
setHasOptionsMenu(true);
submit_post_exact_location = (EditText) rootView
.findViewById(R.id.submit_post_exact_location);
submit_post_exact_time = (TextView) rootView
.findViewById(R.id.submit_post_exact_time);
selected_country = (TextView) rootView
.findViewById(R.id.selected_country);
selected_city = (TextView) rootView.findViewById(R.id.selected_city);
location = new ArrayList<String>();
setListeners();
return rootView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu items for use in the action bar
inflater.inflate(R.menu.mymenu, menu);
// Here we get the action view we defined
myActionMenuItem = menu.findItem(R.id.my_action);
View actionView = myActionMenuItem.getActionView();
// We then get the button view that is part of the action view
if (actionView != null) {
myActionButton = (Button) actionView.findViewById(R.id.action_btn);
myActionButton.setText(R.string.txt_next);
if (myActionButton != null) {
// We set a listener that will be called when the return/enter
// key is pressed
myActionButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
actionBar.setSelectedNavigationItem(2);
}
});
}
}
}
public interface setLocationInfo {
public void pass_location_details(List<String> location);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
info = (setLocationInfo) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ "must implement setLocationInfo");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//setLocationDetails();
}
@Override
public void onPause() {
super.onPause();
setLocationDetails(); ----> doesnt executes since onPause isnt called when I navigate to 3rd fragment as it is an adjacent fragment of this fragment
// Log.d("location : onPause", area);
}
private void setLocationDetails() {
try {
exact_location = submit_post_exact_location.getText().toString();
exact_time = submit_post_exact_time.getText().toString();
country = selected_country.getText().toString();
city = selected_city.getText().toString();
if (country != null && country.length() > 0
&& !country.equalsIgnoreCase("select") && city != null
&& city.length() > 0 && !city.equalsIgnoreCase("select")
&& exact_location != null && exact_location.length() > 0
&& exact_time != null && exact_time.length() > 0) {
location.add(country);
location.add(city);
location.add(exact_location);
location.add(exact_time);
info.pass_location_details(location);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my 3rd Fragment I am trying to get this values
public class PersonalInfoFragment extends Fragment {
List<String> post_details;
List<String> location;
Button submit;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_personal_info,
container, false);
submit = (Button)rootView.findViewById(R.id.submitBtn);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//performing operations with the values obtained
setPostItems();
insertintodb();
}
});
return rootView;
}
public void get_post_details(List<String> post_details,
ArrayList<CustomGallery> selected) { -->receiving values from
this.post_details = post_details; 1st fragment
this.selected = selected;
Log.d("personalfrag(postinfo)", "hello" + post_details.get(5));
}
//receiving values from 2nd fragment
public void get_post_location_details(List<String> location) {
this.location = location;
Log.d("personalfrag(locationinfo)", "hello" + location.get(0));
}
}
Okay, I Had same issue to pass data(not just string) between two tabs in a ViewPager. So here is what i did. I Use interfaces to communicate between the different components.
The data passes this way:
Tab 1 -> Activity -> VewPageAdapter -> Tab 2
Not many would say its a good approach but... meh.. it works :D
- In Tab 1
create an interface.
OnCartsDataListener mOncarOnCartsDataListener;
public interface OnCartsDataListener {
public void onCartsDataReceived(ArrayList<CartsViewModel> cartsViewModels);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOncarOnCartsDataListener = (OnCartsDataListener)activity;
}catch (ClassCastException e){
}
}
// now call mOncarOnCartsDataListener.onCartsDataReceived(data) when you have the data
- In Activity
Implement the interface and override the method
ViewPagerAdapter adapter;
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
@Override
public void onCartsDataReceived(ArrayList<CartsViewModel> cartsViewModels) {
Log.d(TAG, "data received to Activity... send to view pager");
adapter.onCartsDataReceived(cartsViewModels);
}
3.IN ViewPagerAdapter
Also implements the interface and override the method
@Override
public void onCartsDataReceived(ArrayList<CartsViewModel> cartsViewModels) {
Log.d(TAG, "data received to view pager... sending to tab 2");
if(tab2!=null){
tab2.onCartsDataReceived(cartsViewModels);
}else{
Log.d(TAG, "tab2 is null");
}
}
- Finally tab 2
Also implements the interface and override the method
@Override
public void onCartsDataReceived(ArrayList<CartsViewModel> cartsViewModels) {
Log.d(TAG, "Finally ! received data to tab 2");
if(cartsViewModels!=null){
for(CartsViewModel cart : cartsViewModels){
Log.d(TAG,"got it :"+cart.getCartName());
}
}
}
这篇关于Android的:最好的方法来传递viewpager片段之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!