
我在VIEwPager活动中有3个片段.所有3个片段都有输入字段.在这里,我试图将前两个片段数据传递给第三个片段.我在这里阅读了一些帖子,其中大多数建议使用接口(即通过父活动传递数据)
我也经历过这个链接
http://developer.android.com/training/basics/fragments/communicating.html
接口:当我们通过某个用户事件发送数据时,使用接口是很好的方法.这里我试图在没有任何用户事件的情况下发送数据.因此我想到onPause()因为总是调用onPause().但VIEwPager的功能不同.加载片段时,也会加载相邻的片段.我会成功地在第一个片段和第三个片段之间传递数据.但是第二个片段的onPause()不会被调用,除非我导航到一些与它不相邻的片段(在我的情况下不存在)
Setter / Getters:我在几篇帖子中读过人们说不要使用二传手/吸气剂(我还没理解原因)Are getters and setters poor design? Contradictory advice seen
捆绑:我还没考虑过这个.由于我在这里再次感到困惑,我将如何使用bundle传递数据.(我应该在哪个方法中发送数据?以及如何?)
对不起,如果我的问题听起来很愚蠢.我正在尝试理解片段,我想知道在vIEwpager中片段之间传递数据的最佳方法.
先感谢您.
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(这里我试图使用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); } }); } } }}第二片段 – >
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(); } }}在我的第三篇片段中,我试图获得这些价值观
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)); } }解决方法:
好的,我有同样的问题在VIEwPager中的两个标签之间传递数据(不仅仅是字符串).所以这就是我所做的.
我使用接口在不同组件之间进行通信.
数据以这种方式传递:
Tab 1 -> Activity -> VewPageAdapter -> Tab 2>在表1中
创建一个接口.
OnCartsDataListener mOncarOnCartsDataListener;public interface OnCartsDataListener { public voID onCartsDataReceived(ArrayList<Cartsviewmodel> cartsviewmodels);}@OverrIDepublic voID onAttach(Activity activity) { super.onAttach(activity); try { mOncarOnCartsDataListener = (OnCartsDataListener)activity; }catch (ClassCastException e){ }}// Now call mOncarOnCartsDataListener.onCartsDataReceived(data) when you have the data>在活动中
实现接口并覆盖该方法
VIEwPagerAdapter adapter;adapter = new VIEwPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);@OverrIDepublic voID onCartsDataReceived(ArrayList<Cartsviewmodel> cartsviewmodels) { Log.d(TAG, "data received to Activity... send to vIEw pager"); adapter.onCartsDataReceived(cartsviewmodels);}3.在VIEwPagerAdapter中
还实现了接口并覆盖了该方法
@OverrIDepublic 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"); }} >最后选项卡2
还实现了接口并覆盖了该方法
@OverrIDepublic 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片段之间传递数据的最佳方法全部内容,希望文章能够帮你解决Android:在viewpager片段之间传递数据的最佳方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)