方法" onCreateView"在Class" PlaceholderFragment"

时间:2016-02-25 07:38:11

标签: android android-fragments

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            ArrayList<View> rootView = new ArrayList<>();
            View root1 = inflater.inflate(R.layout.fragment1_main_page, container, false);
            View root2 = inflater.inflate(R.layout.fragment2_main_page, container, false);
            View root3 = inflater.inflate(R.layout.fragment3_main_page, container, false);
            View root4 = inflater.inflate(R.layout.fragment4_main_page, container, false);
            rootView.add(root1);
            rootView.add(root2);
            rootView.add(root3);
            rootView.add(root4);
            switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
                case 1:
                    View v = rootView.get(0);
                    Button butt1 = (Button) v.findViewById(R.id.butt1);
                    final TextView text1 = (TextView)v.findViewById(R.id.section_label);
                    butt1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            text1.setText("Hello");
                        }
                    });
                    return v;
                case 2:
                    return rootView.get(1);
                case 3:
                    return rootView.get(2);
                case 4:
                    return rootView.get(3);
                default:
                    return null;
            }
        }
  

这是我的代码,

     

使用switch处理View和Listener时代码太长了,我并不知道将这些代码放到独立的类文件中。请帮忙

1 个答案:

答案 0 :(得分:0)

选择这种方式

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



            switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
                case 1:
                    View root1 =  inflater.inflate(R.layout.fragment1_main_page, container, false);
                      setListener(root1);
                    return root1;
                case 2:
                    View root2 = inflater.inflate(R.layout.fragment2_main_page, container, false);
                    return root2
                case 3:
                    View root3 = inflater.inflate(R.layout.fragment3_main_page, container, false);
                    return root3;

                default:
                    return null;
            }
        }

创建一个用于设置Listener

的新方法
 private void setListener(View root1) {

  // you can do declaration and set Listener here 

    }