[英]How can i use Multiple layout with same ID's in a Single fragment using ViewBinding in Android
The below code to return the any layout based on the condition check,and Both layout's are same id's , Then how to handle the Textview setText() or Button onClick() scenario in this layout Using ViewBinding.下面的代码根据条件检查返回任何布局,并且两个布局的 id 相同,然后如何使用 ViewBinding 处理此布局中的 Textview setText() 或 Button onClick() 场景。
For example, Suppose we used the any Textview setText(" ") in that inflated layout, Then how can i get which layout object name( binding or binding1 ) are should be set the value of the Textview.例如,假设我们在那个膨胀的布局中使用了任何 Textview setText(" "),那么我如何才能得到哪个布局 object 名称(绑定或绑定 1)应该设置Textview的值。
Code:代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
FirstLayoutBinding binding = FirstLayoutBinding.inflate(inflater,container,false);
SecondLayoutBinding binding1 = SecondLayoutBinding.inflate(inflater,container,false);
if (isTrue){
view = binding.getRoot();
}else {
view = binding1.getRoot();
}
return view;
}
Okay let's assume based on your condition check fragment
will inflate the SecondLayoutBinding
layout.好的,让我们假设基于您的条件检查fragment
将膨胀SecondLayoutBinding
布局。
Now you have two different TextViews
in layouts.现在您在布局中有两个不同的TextViews
。
In second_layout.xml
you have TextView
with android:id
attribute value second_text
在second_layout.xml
你有TextView
和android:id
属性值second_text
In first_layout.xml
you have TextView
with android:id
attribute value first_text
在first_layout.xml
你有TextView
和android:id
属性值first_text
Once fragment
completes inflating in onCreateView()
with condition.一旦fragment
在有条件的onCreateView()
中完成膨胀。 Let's set the text value to the inflated layout's TextView
only.让我们将文本值设置为仅膨胀布局的TextView
。
So now we inflated with binding SecondLayoutBinding
and we should setText()
inside that layout with id second_text
in onViewCreated()
.因此,现在我们通过绑定SecondLayoutBinding
进行了膨胀,我们应该在该布局内设置setText()
并在onViewCreated()
中使用 id second_text
。
onViewCreated()
if (!isTrue) {
binding1.secondText.setText("MySecondValue");
} else {
binding.firstText.setText("MyFirstValue");
}
One thing you again need to do is, you have check again which view's id you are trying to call to set it's value.您再次需要做的一件事是,您再次检查您尝试调用哪个视图的 ID 来设置它的值。 If first_layout get's inflated you cannot set value for views or TextView
inside second_layout and vice-versa.如果 first_layout 得到膨胀,则不能在 second_layout 中为视图或TextView
设置值,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.