如何只显示有值的文本视图?
How do I display only textviews that have values?
如果我有 10 个文本视图,我如何有效地显示那些有值的那些并隐藏那些没有值而不检查它们是否有值然后将 visibility
设置为 VISIBLE
每个文本视图。有没有有效的方法来做到这一点?
文本视图在 LinearLayout
内
您将在代码中有一个地方进行此检查。
如果您想删除此检查生成的样板文件,我建议您使用这样的 kotlin 扩展函数:
fun TextView.setTextOrGone(text: String?) {
this.visibility = if (text.isNullOrBlank()) View.GONE else View.VISIBLE
this.text = text
}
然后像这样设置文本:
textView.setTextOrGone(value)
您可以创建一个自定义文本视图,如果没有任何文本可显示,它会自行隐藏。
public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {
public CustomTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
if (getText().toString().isEmpty()){
setVisibility(GONE);
}else{
setVisibility(VISIBLE);
}
}
}
如果我有 10 个文本视图,我如何有效地显示那些有值的那些并隐藏那些没有值而不检查它们是否有值然后将 visibility
设置为 VISIBLE
每个文本视图。有没有有效的方法来做到这一点?
文本视图在 LinearLayout
您将在代码中有一个地方进行此检查。
如果您想删除此检查生成的样板文件,我建议您使用这样的 kotlin 扩展函数:
fun TextView.setTextOrGone(text: String?) {
this.visibility = if (text.isNullOrBlank()) View.GONE else View.VISIBLE
this.text = text
}
然后像这样设置文本:
textView.setTextOrGone(value)
您可以创建一个自定义文本视图,如果没有任何文本可显示,它会自行隐藏。
public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {
public CustomTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
if (getText().toString().isEmpty()){
setVisibility(GONE);
}else{
setVisibility(VISIBLE);
}
}
}