2016年9月27日 星期二

update activity data from gragment



直接看code吧....

當點選   原本的   textview   ..就會觸發 onclickListener...

然後呼叫  List<Fragment> allFragments = getActivity().getSupportFragmentManager().getFragments();

得到bindof 的activity 的 all fragment...存放在allFragments

然後利用   for loop 和  instanceof 來判斷...

是屬於  PersionalFragment..  就呼叫  updateData()..來更新textview的文字....

有了這個solution... 就可以做到改變fragment 的資料

 for (Fragment fragment : allFragments) {
                        if(fragment instanceof  PersionalFragment) {
                            PersionalFragment f = (PersionalFragment) fragment;
                            f.updateData();
                            Toast.makeText(thiscontext, "PersionalFragment  exist", Toast.LENGTH_SHORT).show();
                        }
                    }


================================================
public class PersionalFragment extends Fragment {

    TextView textView;
    Context thiscontext;
    View v2;

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

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_persional, container, false);
      //       v2 =  inflater.inflate(R.layout.activity_main, container, false);        thiscontext = container.getContext();

        textView = (TextView)v.findViewById(R.id.textView);

        textView.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                /*               
                */
                List<Fragment> allFragments = getActivity().getSupportFragmentManager().getFragments();
                if (allFragments != null) {
                    for (Fragment fragment : allFragments) {
                        if(fragment instanceof  PersionalFragment) {
                            PersionalFragment f = (PersionalFragment) fragment;
                            f.updateData();
                            Toast.makeText(thiscontext, "PersionalFragment  exist", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                /*                MainActivity activity = (MainActivity)getActivity();
                ViewPagerAdapter adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());                PersionalFragment a = (PersionalFragment)adapter.getItem(0);                a.updateData();                */                //getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.persional,new PersionalDetailFragment()).commit();
                Toast.makeText(thiscontext, "text onclick", Toast.LENGTH_SHORT).show();

            }
        });

        return v;
    }

    public void updateData(){
        textView.setText("Changed");
    }

}

沒有留言:

張貼留言