如何在recyclerview中找到项目的宽度?

时间:2018-05-23 14:17:15

标签: android android-recyclerview kotlin

我有一个@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class WebsMessagingEncryptionPocApplicationTests { @Autowired private MessageProducer producer; @Autowired private MessageListener messageListener; /** * Ensure that a message is sent, and received. */ @Test public void testProducer() throws Exception{ //ARRANGE CountDownLatch latch = new CountDownLatch(1); messageListener.setCountDownLatch(latch); Transaction trx = new Transaction(); trx.setCustomerAccountID(new BigInteger("111111")); Map<String,Object> jmsHeaders = new HashMap<String,Object>(); jmsHeaders.put("tid", "1234563423"); MessagePostProcessor encryptPostProcessor = new EncryptMessagePostProcessor(); //ACT producer.publishMsg(trx, jmsHeaders, encryptPostProcessor); latch.await(); //ASSERT - assertion done in the consumer } } ,它只是一个水平的按钮列表。我试图创建以下行为:

如果组合的所有按钮的总宽度小于屏幕的总宽度,请将每个按钮的宽度设置为(screenWidth /按钮数)。

我正在测试一些基本代码,以便在我的recyclerview类中获取/设置按钮宽度:

adapter

奇怪的是,虽然此代码实际上将按钮的宽度更改为1080,但在设置按钮宽度之前/之后,两个 override fun onBindViewHolder(holder: TabViewHolder, position: Int) { Log.d("TEST-APP","Button Width: " + holder.button.width.toString()) holder.button.width = 1080 Log.d("VED-APP","New Button Width: " + holder.button.width.toString()) holder.button.text = items[position].first holder.button.setOnClickListener { (context as MainActivity).updateCurrentImageLayout(items[position].second) } } 函数的输出均为0.

如何获得按钮的实际宽度?

这是我的布局,用于定义Log中的一列:

recyclerview

1 个答案:

答案 0 :(得分:1)

Android仅在测量后返回窗口小部件的宽度,并且会在调用onBindViewHolder之后发生。

您可以延迟请求:

holder.button.post {
    Log.d("VED-APP","New Button Width: " + holder.button.width.toString()) 
};