notifydatasetchange在片段之间不起作用?

时间:2015-11-23 10:52:37

标签: android android-fragments

我怀疑我有两个片段,即frag a和相同活动的frag b需要将数据从b传递给a。来自b的数据需要动态填充listview我试过notifydatasetchange()但是到目前为止它还没有用到我试过的是

片段b:

   package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class NewRequirements extends Fragment {
    Add add;
    customListAdapterldrequirements customListAdapterldrequirements;

    //public static NewRequirements newInstance(Bundle bundle) {

    //     Add myFragment = new Add();
    //    myFragment.setArguments(bundle);
    //}

    // }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View view = inflater.inflate(R.layout.fragment_dialog_claim, container,
                false);
        final Button btnupdate;
        btnupdate = (Button) view.findViewById(R.id.update);
        final Spinner sbu = (Spinner) view.findViewById(R.id.sbuu);
        final EditText requiremtns=(EditText)view.findViewById(R.id.txtEmployeeCode);
        final ArrayAdapter<CharSequence> adaptersbu = ArrayAdapter.createFromResource(
                getActivity().getBaseContext(), R.array.newrequirements, R.layout.spinnerlayout);
        adaptersbu.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sbu.setAdapter(adaptersbu);
        final Spinner bu = (Spinner) view.findViewById(R.id.bu);
        final ArrayAdapter<CharSequence> adapterbu = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.newrequirements, R.layout.spinnerlayout);
        adapterbu.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        bu.setAdapter(adapterbu);
        final Spinner sbuu = (Spinner) view.findViewById(R.id.sbu);
        final ArrayAdapter<CharSequence> adaptersbuu = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.newrequirements, R.layout.spinnerlayout);
        adaptersbuu.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sbuu.setAdapter(adaptersbuu);
        final Spinner sc = (Spinner) view.findViewById(R.id.sc);
        ArrayAdapter<CharSequence> adaptersc = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.newrequirements, R.layout.spinnerlayout);
        adaptersc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sc.setAdapter(adaptersc);
        final Spinner ssc = (Spinner) view.findViewById(R.id.ssc);
        ArrayAdapter<CharSequence> adapterssc = ArrayAdapter.createFromResource
                (getActivity().getBaseContext(), R.array.newrequirements, R.layout.spinnerlayout);
        adapterssc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ssc.setAdapter(adapterssc);
        setHasOptionsMenu(true);
Add add=(Add)getFragmentManager().findFragmentByTag("leads");
        add.updateListView();

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String str = sbu.getSelectedItem().toString();
       String business_unit=         bu.getSelectedItem().toString();
                String sub_business_unit=sbuu.getSelectedItem().toString();
String service=sc.getSelectedItem().toString();
                String servicec=ssc.getSelectedItem().toString();

                String req=requiremtns.getText().toString();
                FragmentManager fm = getFragmentManager();
                Add add = new Add();

                // bundle.putString("yes", str);
                //    Log.i("Bundle", bundle.toString());
                //    Log.v("Add", str);
                // add.setArguments(bundle);
                Main2Activity.sbu=str;
                Main2Activity.bu=business_unit;
                Main2Activity.sbuu=sub_business_unit;
                Main2Activity.sc=service;
                Main2Activity.ssc=servicec;
                Main2Activity.req=req;
                FragmentTransaction ft = fm.beginTransaction();
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.replace(R.id.content_frame, add, "hi");

                //add.lv.setVisibility(View.VISIBLE);
                ft.addToBackStack(null);
                ft.commit();


            }

        });
        return view;
    }

}

片段a:

   package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by 4264 on 16-10-2015.
 */
public  class Add extends Fragment implements View.OnClickListener
{
    private ListView lv;
 static    String  sbu,sbuu,sc,ssc,req;
    static String bu;
    static boolean single;
    Add add;

    customListAdapterldrequirements cus;
    private ArrayList<LdNewsItem>ldnews;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        try {
            View rootView = inflater.inflate(R.layout.activity_btn_add, container, false);
            Spinner ldsource=(Spinner)rootView.findViewById(R.id.lead_source);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox1, R.layout.spinnerlayout);


            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            ldsource.setAdapter(adapter);
            //   EditText editText=(EditText)rootView.findViewById(R.id.title);

            Spinner ldtype=(Spinner)rootView.findViewById(R.id.ldtype);
            ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox2,R.layout.spinnerlayout);

            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            ldtype.setAdapter(adapter1);
            Spinner ldstatus=(Spinner)rootView.findViewById(R.id.ldstatus);
            TextView txt=(TextView)rootView.findViewById(R.id.spinnerTarget);
            ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                    getActivity().getBaseContext(), R.array.dropbox3, R.layout.spinnerlayout);

            adapter2.setDropDownViewResource(android.R.layout.simple_selectable_list_item);
            ldstatus.setAdapter(adapter2);
            //  Bundle bundle=getArguments();
            //  String good=bundle.getString("sbu");




            Bundle bundle=getArguments();

//            sbu = getArguments().getString("yes");


            //    public boolean onTouch(View v, MotionEvent event) {
            //        return false;
            // }

            // Setting on Touch Listener for handling the touch inside ScrollView


            //});

            lv = (ListView) rootView.findViewById(R.id.ldrequirements);
//customListAdapterldrequirements customListAdapterldrequirements=new customListAdapterldrequirements(getActivity(),listContact);

            ArrayList<LdNewsItem> listContact = GetlistContact();
            lv.setAdapter(new customListAdapterldrequirements(getActivity(), listContact));
customListAdapterldrequirements customListAdapterldrequirements=new customListAdapterldrequirements(getActivity(),listContact);

            //   cus=new customListAdapterldrequirements(this,ldnews);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {

                    if (single) {
                        NewRequirements newRequirements = new NewRequirements();
                        FragmentManager fm = getFragmentManager();
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

                        //  lv.deferNotifyDataSetChanged();
                        ft.replace(R.id.content_frame, newRequirements, "hi");
                        ft.addToBackStack(null);
                        ft.commit();

                    } else {

                        lv.getItemIdAtPosition(position);
                    }
                }
            });
      /*  lv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }


            // Setting on Touch Listener for handling the touch inside ScrollView
      //      @Override
        //    public boolean onTouch(View v, MotionEvent event) {
                // Disallow the touch request for parent scroll on touch of child view

          //      v.getParent().requestDisallowInterceptTouchEvent(true);
//
  //              return false;
    //        }
        });*/
            return rootView;

        }catch (Exception e){
            throw e;
        }
    }




    private ArrayList<LdNewsItem> GetlistContact()
    {
        ArrayList<LdNewsItem> contactlist = new ArrayList<LdNewsItem>();
        //    String str=getArguments().getString("yes");


        //   String str="test";
        //  NewRequirements newr=new NewRequirements();
//        String yog=getArguments().getString("sbu");
//        sbu.notify();
        sbu=Main2Activity.sbu;
        bu=Main2Activity.bu;
        sbuu=Main2Activity.sbuu;
        sc=Main2Activity.sc;
        ssc=Main2Activity.ssc;
        req=Main2Activity.req;
        for(int i=1;i<=5;i++) {
            LdNewsItem    contact = new LdNewsItem();
            contact.setSbu(sbu);
            contact.setBu(bu);
            contact.setSbuu(sbuu);
            contact.setSc(sc);
            contact.setSsc(ssc);
            contact.setReq(req);
            // contact.setReporterName("No matter how big your house is, how recent your car is, or how big your bank account is — our graves will always be the same size. Stay humble." + i);
            contactlist.add(contact);
//lv.setAdapter((ListAdapter) contactlist);

        }

        return contactlist;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Fragment fragment=null;
        setHasOptionsMenu(true);
        Button btnrequirements=(Button)getActivity().findViewById(R.id.btnrequirements);
        btnrequirements.setOnClickListener(this);
        Button btnactnt=(Button)getActivity().findViewById(R.id.btnacnt);
        btnactnt.setOnClickListener(this);
        Button btnprimary=(Button)getActivity().findViewById(R.id.btnprimary);
        btnprimary.setOnClickListener(this);
        Button btnsecondary=(Button)getActivity().findViewById(R.id.btnsecondary);
        btnsecondary.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnrequirements:
                Fragment newFragment = new NewRequirements();
                // consider using Java coding conventions (upper first char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                // Commit the transaction
                transaction.commit();
                break;

            case R.id.btnacnt:
                FragmentManager fm=getFragmentManager();
                //FragmentTransaction ft=fm.beginTransaction();
                SelectAccountDialog selectAccountDialog=new SelectAccountDialog();
                selectAccountDialog.setRetainInstance(true);
                selectAccountDialog.show(fm, "fragment_name");

                //ft.addToBackStack(null);

                break;
            case R.id.btnprimary:
                FragmentManager fmm=getFragmentManager();
                // FragmentTransaction ftt=fmm.beginTransaction();
                SelectAccountDialog selectAccountDialog1=new SelectAccountDialog();
                selectAccountDialog1.setRetainInstance(true);
                selectAccountDialog1.show(fmm, "fragment_name");
                //   ftt.addToBackStack(null);
                break;
            case R.id.btnsecondary:
                FragmentManager fm2=getFragmentManager();
                //     FragmentTransaction fttt=fm2.beginTransaction();
                SelectAccountDialog selectAccountDialog2=new SelectAccountDialog();
                selectAccountDialog2.setRetainInstance(true);
                selectAccountDialog2.show(fm2,"fragment_name");
                //     fttt.addToBackStack(null);
                break;

        }

    }


    public void updateListView() {
   cus.notifyDataSetChanged();
    }
}

这是我的customlistadapter:

  package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by 4264 on 12-11-2015.
 */
public class customListAdapterldrequirements extends BaseAdapter{

    Add add;
    private ArrayList<LdNewsItem> listData;
    private LayoutInflater layoutInflater;

    public customListAdapterldrequirements(Context context, ArrayList<LdNewsItem> listData) {
        this.listData = listData;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return listData.size();
    }

    @Override
    public Object getItem(int position) {

        return listData.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        View mview = convertView;

        // convertView.setBackgroundColor(Color.parseColor("#E5E5E5"));

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.list_ld_requirements, null);

            holder = new ViewHolder();
            holder.headlineView = (TextView) convertView.findViewById(R.id.sbu);
            holder.reporterNameView = (TextView) convertView.findViewById(R.id.bu);
            holder.reportedDateView = (TextView) convertView.findViewById(R.id.sbuu);
            holder.ldstatusView = (TextView) convertView.findViewById(R.id.sc);
            holder.ldtype = (TextView) convertView.findViewById(R.id.ssc);
            holder.ldsource = (TextView) convertView.findViewById(R.id.rq);
        //    add.lv.setVisibility(View.INVISIBLE);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
    //    add.lv.setVisibility(View.VISIBLE);
        holder.headlineView.setText("Strategic Business Unit: " + listData.get(position).getSbu());
        holder.reportedDateView.setText("Business Unit: " + listData.get(position).getSbuu());
        holder.ldstatusView.setText("Sub Business Unit: " + listData.get(position).getSc());
        holder.ldtype.setText("Service Category: " + listData.get(position).getSsc());
        holder.ldsource.setText("Service Sub Category: " + listData.get(position).getReq());


        convertView.setBackgroundColor(Color.parseColor("#E5E5E5"));



        // holder.headlineView.setText("Requirements: " +listData.get(position).getReq());


        return convertView;
    }

    static class ViewHolder {
        public TextView headlineView;
        public TextView reporterNameView;
        public TextView reportedDateView;
        public TextView ldstatusView;
        public TextView ldtype;
        public TextView ldsource;
        public TextView req;
    }
}

我的主要活动:

package first.service.precision.servicefirst;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


public class Main2Activity extends Activity  {

    public static String sbu,bu,sbuu,sc,ssc,req;

    // Within which the entire activity is enclosed
    private DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    private ListView mDrawerList;
    Button butonlead;
    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    private ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        final ActionBar ab = getActionBar();
        ab.show();
        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ab.setTitle(mTitle);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

                R.string.open_drawer,
                R.string.close_drawer) {

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {

                invalidateOptionsMenu();

            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {

                invalidateOptionsMenu();
            }


        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
                R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        ab.setHomeButtonEnabled(true);
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
        // Enabling Up navigation
        ab.show();
        ab.setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // Getting an array of options
                String[] menuItems = getResources().getStringArray(R.array.option);

                // Currently selected option
                mTitle = menuItems[position];

                Fragment fragment = null;
                switch (position) {
                    case 0:
                        fragment = new Leads();
                        break;
                    case 1:
                        fragment = new Opportunities();
                        break;
                    case 2:
                        fragment = new Accounts();
                        break;
                    case 3:
                        fragment = new Contactss();
                        break;
                    case 4:
                        fragment = new Documents();
                        break;
                    case 5:
                        fragment = new Reports();
                    default:
                        break;
                }
                if (fragment != null) {
                    // Getting reference to the FragmentManager
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("fragback").commit();
                    // Creating a fragment transaction
                    FragmentTransaction ft = fragmentManager.beginTransaction();

                    // Adding a fragment to the fragment transaction
                    ft.replace(R.id.content_frame, fragment);

                    // Committing the transaction
                    ft.commit();

                    // Closing the drawer
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    // error in creating fragment
                    Log.e("MainActivity", "Error in creating fragment");
                }

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            super.onBackPressed();
        }

    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Called whenever we call invalidateOptionsMenu()
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);


        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main2, menu);
        return super.onCreateOptionsMenu(menu);
    }



   /* @Override
    public void DataTransfer(String e) {


    }*/
//
    // @Override
    //  public void DataTransfer(ArrayList<String> e) {
    //     Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
    //   obj.GetlistContact(e);
    // }
}
  /*  @Override
    public void selectedvalue(String s) {
            Add add=new Add();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.content_frame,add);
            ft.commit();}
    }
*/

我希望你们在这里帮助我们像我们这样的初学者提前感谢!

1 个答案:

答案 0 :(得分:0)

您好,您可以使用fragB中的片段TAGS从frag b更新您的frag a,您可以这样调用,

document.createElement("html")

现在如何声明标签....

  
    

您可以在片段附加到MainActivity

中的容器时指定标记名   
  public static string PostRequesttoYammer(string postBody, string url,string authHeader = null, string contentType = null)
    {
        string results = string.Empty;
        try
        {
            HTTPWebReq = WebRequest.CreateHttp(url);
            HTTPWebReq.Method = "POST";
            if (!string.IsNullOrEmpty(authHeader))
                HTTPWebReq.Headers.Add("Authorization: Bearer " + authHeader);
            byte[] postByte = Encoding.UTF8.GetBytes(postBody);
            if (string.IsNullOrEmpty(contentType))
                HTTPWebReq.ContentType = "application/x-www-form-urlencoded";
            else
                HTTPWebReq.ContentType = contentType;
            HTTPWebReq.ContentLength = postByte.Length;
            Stream postStream = HTTPWebReq.GetRequestStream();
            postStream.Write(postByte, 0, postByte.Length);
            postStream.Close();
            HTTPWebRes = (HttpWebResponse)HTTPWebReq.GetResponse();
            postStream = HTTPWebRes.GetResponseStream();
            StreamReader postReader = new StreamReader(postStream);
            results = postReader.ReadToEnd();
            postReader.Close();
            postStream.Close();
        }
        catch (Exception ex)
        {
        }
        return results;
    }

:)