在Fragment之间共享数据不要更新

时间:2013-10-23 11:33:41

标签: android android-fragments fragment share

我有4个Fragment Sector1,2,3,4,我想在Fragment之间传输数据。 当我在扇区1中添加产品时,相同的产品将插入Sector2中的Edit中。 如果我在扇区1和2之间切换没问题,但是当我转到Sector3并返回到扇区1以插入另一个产品时,新产品不会出现在Sector2上的Edit中。 为什么? (这是第一个问题),我在Sector 1和Sector3之间实现了相同的共享数据,但没有添加任何产品为什么? (这是第二个问题)

这里是文件:

MainActivity.java

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, 
                                                                OnShareMyDataListener{

    private static final String TAG = "MainActivity";

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;  
    ViewPager mViewPager;

    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "MainActivity.onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Settare il tipo di navigazione
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
        final ActionBar actionBar = getActionBar();

        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
            }
        });

        // creo icona e scritta per il 1 Tab
        Tab tab = actionBar.newTab()
                .setText("Ordine")
                .setTabListener(this)
                .setIcon(R.drawable.ic_menu_agenda);
        actionBar.addTab(tab);

        // creo icona e scritta per il 2 Tab
        tab = actionBar.newTab()
                .setText("by Mail")
                .setTabListener(this)
                .setIcon(R.drawable.ic_menu_send);
        actionBar.addTab(tab);

        // creo icona e scritta per il 3 Tab
        tab = actionBar.newTab()
                 .setText("by SMS")
                 .setTabListener(this)
                 .setIcon(R.drawable.phone);
        actionBar.addTab(tab);      

        // creo icona e scritta per il 4 Tab
        tab = actionBar.newTab()
                 .setText("Feedback")
                 .setTabListener(this)
                 .setIcon(R.drawable.ic_menu_revert);
        actionBar.addTab(tab);      

    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }


    public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

        public AppSectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

// Il return new chiama le altre classi (i Fragment) 
        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:                  
                    return new Sector1();

                case 1:
                    return new Sector2();

                case 2:
                    return new Sector3();

                case 3:
                    return new Sector4(); 

                default:                   
                    Fragment fragment = new Sector1();
                    Bundle args = new Bundle();

                    fragment.setArguments(args);
                    return fragment;
            }
        }

// Settare il titolo dei Sector
        @Override
        public int getCount() {
            return 4;
        }
    }

    @Override
    public void onShareMyData(ArrayList<User> data) {
        // TODO Auto-generated method stub
         Sector2 Sector2Obj = (Sector2) getSupportFragmentManager().findFragmentById(R.id.pager);
         Sector2Obj.setMessage(data);   

         Sector3 Sector3Obj = (Sector3) getSupportFragmentManager().findFragmentById(R.id.pager);
         Sector3Obj.setMessage(data);
    }

}

activity_main.xml中

<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Sector1.java

public class Sector1 extends Fragment 
{   
    private Button btnAggiungi;
    private EditText EtQta,EtName;

    ListView userList;

    ArrayList<User> userArray = new ArrayList<User>();

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.sector1, container, false);

            btnAggiungi = (Button) rootView.findViewById(R.id.btn_aggiungi);
            EtQta = (EditText) rootView.findViewById(R.id.Et_qta);
            EtName = (EditText) rootView.findViewById(R.id.Et_name);

            btnAggiungi.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub          
                    try {                           
                        String Qta = "Qtà: "+ String.valueOf(EtQta.getText());
                        String Prodotto = "prodotto: "+ String.valueOf(EtName.getText());

                        userArray.add(new User(Prodotto, Qta));

                        sharedData.onShareMyData(userArray);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }                       
                }       
            });         

            //return super.onCreateView(inflater, container, savedInstanceState);
             return rootView;
        }

        OnShareMyDataListener sharedData;

        @Override
           public void onAttach(Activity activity) {
               super.onAttach(activity);
               try {
                   sharedData = (OnShareMyDataListener) activity/*getActivity()*/;
               } catch (ClassCastException e) {
                   throw new ClassCastException(activity.toString() + " must implement onShareMyData");
               }
           }   


        /**
         * get datetime
         * */
        private String getDateTime() {
            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "dd/MM/yyyy kk:MM", Locale.getDefault());
            Date date = new Date();
            return dateFormat.format(date);
        }

        private String getItemUserArray() {
            String str=null;

            for (int i = 0; i < userArray.size(); i++) {
                str += userArray.get(i).toString();
             }
            return str;
        }

    }

Sector2.java

public class Sector2 extends Fragment
{
    private Button btnSendOrder,btnBrowseContact;
    EditText nameField;
    EditText emailField;
    String subject = null;
    TextView txt;
    View rootView;
    private Spinner mySpinnerEmail;
    ArrayList<String> emailFornitore ;
    ArrayList<String> aEmailList;

        @Override
        public View onCreateView(LayoutInflater inflater, 
                ViewGroup container, Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.sector2, container, false);
            init(rootView);

            return rootView;
        }


        void init(View rootView){


        }  
  /******************************************************************************/      


        void setMessage(ArrayList<User> data){
            String str;

            txt = (TextView)rootView.findViewById(R.id.Et_ordine);

            str = "[" + data.get(0).getName() + "]\n";
            subject = str;
            for (int i = 1; i < data.size(); i++) {
                str += data.get(i).getName() + "(" + data.get(i).getQta() + ")\n";
            }
            txt.setText(str);
        }


    }

Sector3.java

public class Sector3 extends Fragment
{
    Button buttonSend;
    EditText textPhoneNo;
    EditText textSMS;
    TextView sms_count;
    String subject = null;
    TextView txt;
    View rootView;

        @Override
        public View onCreateView(LayoutInflater inflater, 
                ViewGroup container, Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.sector3, container, false);
            init(rootView);

            return rootView;
        }

        void init(View rootView){           

        } 

        void setMessage(ArrayList<User> data){
            String str;

            txt = (TextView)rootView.findViewById(R.id.editTextSMS);

            str = "[" + data.get(0).getName() + "]\n";// + data.get(0).getQta() + "]\n";
            subject = str;
            for (int i = 1; i < data.size(); i++) {
                str += data.get(i).getName() + "(" + data.get(i).getQta() + ")\n";
            }
            txt.setText(str);
        }      


    }

OnShareMyDataListener.java

public interface OnShareMyDataListener {
    public void onShareMyData(ArrayList<User> data);
}

User.java

public class User {
     String name;
     String qta;

     public String getName() {
      return name;
     }

     public void setName(String name) {
      this.name = name;
     }

     public String getQta() {
      return qta;
     }

     public void setQta(String qta) {
      this.qta = qta;
     }

     public User(String name, String qta) {
      super();
      this.name = name;
      this.qta = qta;
     }
    }

1 个答案:

答案 0 :(得分:0)

AppSectionPagerAdapter 扩展了什么? 如果您查看Android Doc,您会看到FragmentPagerAdapter 销毁您片段的查看层次。 因此,当你转到section3时,section1的视图层次结构被破坏,当你返回时,它完全被重新处理,但从头开始。

在您的代码中,主要问题是您要显示的数据未存储。请记住,在Activity [Fragment []]层次结构中,要点是活动,因此您必须将数据存储在Activity中,以便可以从任何地方访问它。

我的建议:

在您的活动中添加一个将更新的字段ArrayList<User> data

 @Override
    public void onShareMyData(ArrayList<User> data) {
        this.data = data;
    }

在你的Sections的 onCreate()

sharedData = (OnShareMyDataListener) activity; 
sharedData.data