【问题标题】:How to get EditText width dynamically and set it to a recyclerView width如何动态获取 EditText 宽度并将其设置为 recyclerView 宽度
【发布时间】:2022-01-17 17:02:53
【问题描述】:

我有一个edittext,它的宽度设置为wrap-content。我还有一个回收器视图,它的宽度设置为wrap-content。我想让回收站视图宽度等于以编程方式编辑文本宽度。我使用了下面的代码,但它不起作用。从 getMeasuredWidth() 返回的宽度不等于 edittext 宽度。

    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);

【问题讨论】:

    标签: java android android-recyclerview android-edittext


    【解决方案1】:

    您应该以<View>.requestLayout() 结尾以使用新大小刷新(当前为employeeRecyclerView)。

    onCreate() 中的观看次数也未正确测量。为了获得editText 的宽度,您可以使用postpostDelayeddoOnPreDraw (onPreDrawListener) 或viewTreeObserver

    【讨论】:

    • requestLayout() 不工作,请提供示例代码。
    • @ISHHANKALANSOORIYA,你调试过应用程序吗?你买了什么尺寸的?我的意思是 TextView 宽度和 RecyclerView 宽度(调整大小之前和之后)?
    • stackoverflow.com/questions/13856180/…。您可以通过编程方式设置 RecyclerView 宽度(例如 layoutParams.width = 1000),然后调用 testRecyclerView.requestLayout()
    • 我确实进行了一些测试,结果发现 recyclerView 正在将 editText 内的文本长度作为其宽度而不是 editText 宽度
    • 使用帖子为我工作,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多