0

我有 4 个 Fragment Sector1、2、3、4,我想在 Fragment 之间传输数据。当我在扇区 1 中添加产品时,相同的产品会插入到扇区 2 的编辑中。如果我在扇区 1 和 2 之间切换没有问题,但是当我转到扇区 3 并返回扇区 1 插入另一个产品时,新产品不会出现在扇区 2 的编辑中。 为什么?(这是第一个问题),我在 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);
}

用户.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;
     }
    }
4

1 回答 1

0

AppSectionPagerAdapter扩展了什么?如果您查看Android Doc,您会看到FragmentPagerAdapter Destroy the view Hierachy of your Fragment。因此,当您转到第 3 节时,第 1 节的视图层次结构被破坏,当您返回时,它完全重新创建,但从头开始。

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

我的建议:

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

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

在您的部分的onCreate()中:

sharedData = (OnShareMyDataListener) activity; 
sharedData.data
于 2013-10-23T12:33:49.610 回答