findViewById in Fragment

后端 未结 30 2249
终归单人心
终归单人心 2020-11-21 06:39

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById<

相关标签:
30条回答
  • 2020-11-21 07:25

    The best way to implement this is as follows:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    rootView = inflater.inflate(R.layout.testclassfragment, container, false);
            ImageView imageView = (ImageView) rootView.findViewById(R.id.my_image);
            return rootView
    }
    

    In this way, the rootView can be used for each control defined in the xml layout and the code is much cleaner in this way.

    Hope this helps :)

    0 讨论(0)
  • 2020-11-21 07:25

    There is one more method called onViewCreated.

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
    }
    
    0 讨论(0)
  • 2020-11-21 07:26

    1) first inflate layout of Fragment then you can use findviewbyId .

    View view = inflater.inflate(R.layout.testclassfragment, container, false);
                 ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
                 return view;
    
    0 讨论(0)
  • 2020-11-21 07:27
    EditText name = (EditText) getView().findViewById(R.id.editText1);
    EditText add = (EditText) getView().findViewById(R.id.editText2);  
    
    0 讨论(0)
  • 2020-11-21 07:28

    Use

    imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
    
    imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
    

    it will work

    0 讨论(0)
  • 2020-11-21 07:28

    Layout inflater comes into picture here. Layout inflater is a class that make us able to use the XML views in java code. So you can inflate the root xml view in variable v with the following code. And then using v, you can find the child views of the root view v.

    public class TestClass extends Fragment {
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.testclassfragment, container, false);
        ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
        return v;
        }
    }
    
    0 讨论(0)
提交回复
热议问题