findViewById in Fragment

后端 未结 30 2247
终归单人心
终归单人心 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:16

    You could also do it in the onActivityCreated Method.

    public void onActivityCreated(Bundle savedInstanceState) { 
          super.onActivityCreated(savedInstanceState);
    }
    

    Like they do here: http://developer.android.com/reference/android/app/Fragment.html (deprecated in API level 28)

    getView().findViewById(R.id.foo);
    

    and

    getActivity().findViewById(R.id.foo);
    

    are possible.

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

    Note :

    From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.

    So now you can simply do,

    public View onCreateView(LayoutInflater inflater, 
                             ViewGroup container, 
                             Bundle savedInstanceState) {
         View view = inflater.inflate(R.layout.testclassfragment, container, false);
         ImageView imageView =  view.findViewById(R.id.my_image); //without casting the return type
         return view;
    }
    
    0 讨论(0)
  • 2020-11-21 07:17

    In fragments we need a view of that window so that we make a onCreateView of this Fragment.

    Then get the view and use it to access each and every view id of that view elements..

      class Demo extends Fragment
        {
            @Override
            public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
            {
                View view =inflater.inflate(R.layout.demo_fragment, container,false);
                ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);
    
                return view;
            }
        }
    
    0 讨论(0)
  • 2020-11-21 07:24

    getView() will give the root view

    View v = getView().findViewByID(R.id.x); 
    
    0 讨论(0)
  • 2020-11-21 07:24

    You can call findViewById() with the Activity Object you get inside your public void onAttach(Activity activity) method inside your Fragment.

    Save the Activity into a variable for example:

    In the Fragment class: private Activity mainActivity; In the onAttach() method: this.mainActivity=activity;

    Finally execute every findViewById through the vairable: mainActivity.findViewById(R.id.TextView);

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

    agreed with calling findViewById() on the View.

    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)
提交回复
热议问题