Jul 30, 2014

fragment






I consist 3 fragments and 1 activity.

First fragment is image page.

Second fragment is button page.

Third  fragment is web page.

And activity has empty layout and 2 button for moving page.

This is activity.

Fragment add to empty layout.


This is image fragment.


This is button fragment.


This is web fragment.



mainActivity.java

mainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void switch_fragment(int state){

    switch (state){
    case image_state:
        ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fraglayout, image, imageFrag);
        //ft.addToBackStack(null);            
        ft.commit();
        btnLeft.setText("button");
        btnRight.setText("web");
        frag_state = 1;
        break;
    case button_state:
        ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fraglayout, button, buttonFrag);
        //ft.addToBackStack(null);            
        ft.commit();
        btnLeft.setText("image");
        btnRight.setText("web");
        frag_state = 2;
        break;
    case web_state:
        ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fraglayout, web, webFrag);
        //ft.addToBackStack(null);            
        ft.commit();
        btnLeft.setText("image");
        btnRight.setText("button");
        frag_state = 3;
        break;
    default:
        break;
    }
}
 


This is switching fragment.

Line 5~8 : changing fragment.

If you active line 7, possible to using back state.

buttonFragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class buttonFragment extends Fragment implements OnClickListener{
 
    Button btn;
    View view;
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.button_frag, container, false);
            init();
 
            return view;
        }
    private void init(){
        btn = (Button)view.findViewById(R.id.btn);
        btn.setOnClickListener(this);
 
    }
    @Override
        public void onClick(View v) {
            switch (v.getId()){
            case R.id.btn:
                Toast.makeText(getActivity(), "hi welcome to button fragment", Toast.LENGTH_SHORT).show();
                break;
            }
 
        }
}
 


Line 14: using view for "findViewById" .

Line 22: using getActivity() instead of context.



No comments:

Post a Comment