2

I have an edittext and its width is set to wrap-content.I also have an recycler view and its width is set to wrap-content. i want to make recycler view width to be equals to edit text width programmatically.I used below code but its not working.width returns from getMeasuredWidth() is not equal to edittext width.

    editText= findViewById(R.id.edit_text);
    editText.measure(0, 0);
    testRecyclerView= findViewById(R.id.employee_recycler_view);
    testRecyclerView.setLayoutManager(new LinearLayoutManager(context));
    ViewGroup.LayoutParams layoutParams =  testRecyclerView.getLayoutParams();
    layoutParams.width =  editText.getMeasuredWidth();
    testRecyclerView.setLayoutParams(layoutParams);

1 Answers1

2

You should end with <View>.requestLayout() to refresh with a new size (currently employeeRecyclerView).

Also views are not correctly measured in onCreate(). In order to get editText width you can use post, postDelayed, doOnPreDraw (onPreDrawListener) or viewTreeObserver.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
  • requestLayout() not working, can you provide an example code please. – ISHAN KALANSOORIYA Dec 14 '21 at 12:15
  • @ISHANKALANSOORIYA, did you debug an application? What sizes did you get? I mean TextView width and RecyclerView width (before and after resizing)? – CoolMind Dec 14 '21 at 13:43
  • https://stackoverflow.com/questions/13856180/usage-of-forcelayout-requestlayout-and-invalidate. You can set RecyclerView width programmatically (for instance, layoutParams.width = 1000) and then call `testRecyclerView.requestLayout()`. – CoolMind Dec 14 '21 at 13:49
  • I did run some tests turns out recyclerView is getting the text length inside the editText as its width not the editText width – ISHAN KALANSOORIYA Dec 14 '21 at 14:56
  • 1
    using post working for me, thank you very much – ISHAN KALANSOORIYA Dec 16 '21 at 07:00
  • @ISHANKALANSOORIYA, glad to hear it! I also used `measure` this way: `someView.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)`, but it works not always and depends on view size (in my case I used `android:layout_width="match_parent"`). – CoolMind Dec 16 '21 at 11:28