2016年7月20日 星期三

Fragment on android






下面是Fragment 的sample....  繼承於Fragment .....

覆寫了 onCreateView()


public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.my_fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.textView);
        String title = getArguments().getString("title");
        textView.setText(title);
        return view;
    }
}


在Mainactivity.java 裡面....  呼叫  getFragmentManager() 得到 manager 



public void onAddClick(View view) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Fragment fragment = manager.findFragmentById(R.id.frameLayout);
        if (fragment == null) {
            String title = "Fragment A";
            MyFragment fragmentA = new MyFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            fragmentA.setArguments(bundle);
            transaction.add(R.id.frameLayout, fragmentA, TAG);
            transaction.commit();
        } else {
            showToast("fragment exists");
        }
    }





沒有留言:

張貼留言