将 data/object 附加到选项卡式布局中的选项卡
Attaching data/object to a tab in tabbed layout
我创建了一个选项卡布局,它为列表中的每个医生对象创建了一个选项卡。 Currently i am setting the tab title as doctor name but when a tab is selected, I want to get the id of the corresponding doctor.我可以从列表中的位置得到这个,但我希望有一个更清洁的解决方案。有什么方法可以在创建时将对象或什至只是一个 id 附加到选项卡,以便我可以在我的侦听器被触发时直接从选定的选项卡访问它?
tabLayout.addTab(tabLayout.newTab().setText("All"));
for(Doctors doctor: list)
{
TabLayout.Tab tempTab = tabLayout.newTab().setText(doctor.getName());
tempTab.setIcon(R.drawable.john_smith_photo);
//here i would like to put doctor.getId() into my tab
tabLayout.addTab(tempTab);
}
您尝试过使用setTag()
方法吗?参见 docs. You can use it in any class that extends View and you can store data with it. To retrieve the data, you can use getTag()
. Also works for TabLayout.Tab.
Tags can also be used to store data within a view without resorting to another data structure.
就这么简单:
tempTab.setTag(doctor.getId());
我创建了一个选项卡布局,它为列表中的每个医生对象创建了一个选项卡。 Currently i am setting the tab title as doctor name but when a tab is selected, I want to get the id of the corresponding doctor.我可以从列表中的位置得到这个,但我希望有一个更清洁的解决方案。有什么方法可以在创建时将对象或什至只是一个 id 附加到选项卡,以便我可以在我的侦听器被触发时直接从选定的选项卡访问它?
tabLayout.addTab(tabLayout.newTab().setText("All"));
for(Doctors doctor: list)
{
TabLayout.Tab tempTab = tabLayout.newTab().setText(doctor.getName());
tempTab.setIcon(R.drawable.john_smith_photo);
//here i would like to put doctor.getId() into my tab
tabLayout.addTab(tempTab);
}
您尝试过使用setTag()
方法吗?参见 docs. You can use it in any class that extends View and you can store data with it. To retrieve the data, you can use getTag()
. Also works for TabLayout.Tab.
Tags can also be used to store data within a view without resorting to another data structure.
就这么简单:
tempTab.setTag(doctor.getId());