get parent's view from a layout

后端 未结 7 2242
囚心锁ツ
囚心锁ツ 2020-12-25 09:54

I have a FragmentActivity with this layout:




        
相关标签:
7条回答
  • 2020-12-25 10:17

    If you are trying to find a View from your Fragment then try doing it like this:

    int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;
    
    0 讨论(0)
  • 2020-12-25 10:20

    The RelativeLayout (i.e. the ViewParent) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId). If you don't do that, the call to getId will return null. Look at this answer for more info.

    0 讨论(0)
  • 2020-12-25 10:20

    Check my answer here

    The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

    0 讨论(0)
  • 2020-12-25 10:24

    This also works:

    this.getCurrentFocus()
    

    It gets the view so I can use it.

    0 讨论(0)
  • 2020-12-25 10:25

    Just write

    this.getRootView();
    
    0 讨论(0)
  • 2020-12-25 10:32

    You can get ANY view by using the code below

    view.rootView.findViewById(R.id.*name_of_the_view*)

    EDIT: This works on Kotlin. In Java, you may need to do something like this=

    this.getCurrentFocus().getRootView().findViewById(R.id.*name_of_the_view*);

    I learned getCurrentFocus() function from: @JFreeman 's answer

    0 讨论(0)
提交回复
热议问题