使用 Android 数据绑定动态切换布局元素的可见性。

2024-04-03

我正在构建一个 Android 应用程序,我想在其中根据按钮单击切换某些视图元素的可见性。我试图使用数据绑定而不是使用 findViewById() 来存档它,但是当变量更改时,我到目前为止找到的所有解决方案都不会更新布局。

这是我到目前为止所拥有的。 (我简化了代码,以集中精力解决问题)

活动.java

public class RecipeActivity extends AppCompatActivity {
private Recipe recipe;
private ActivityRecipeBinding binding;
private RecipeBinderHelper rbhelper = new RecipeBinderHelper();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    recipe = intent.getParcelableExtra("recipe");
    binding = DataBindingUtil.setContentView(this, R.layout.activity_recipe);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(recipe.getName());
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    binding.recipeContent.setRecipe(recipe);
    binding.recipeContent.setHelper(rbhelper);

    binding.Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //HERE I CHANGE THE VALUE OF THE VARIBLE
            rbhelper.setPresentationViewVisible(false);
            binding.notifyChange();
        }
    });
}
}

助手类

public class RecipeBinderHelper{
private Boolean presentationElementsVisible;
private Boolean timerElementsVisible;

public RecipeBinderHelper(){
    this.presentationElementsVisible = true;
    this.timerElementsVisible = false;
}
public void setPresentationViewVisible(boolean presentationElementsVisible) {
    this.presentationElementsVisible = presentationElementsVisible;
}
public Boolean getPresentationElementsVisible() {
    return presentationElementsVisible;
}
//getters and setters for private Boolean timerElementsVisible;
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
    <import type="android.view.View"/>
    <variable
        name="helper"
        type="com.myapps.recipeApp.RecipeBinderHelper"/>
    <variable
        name="recipe"
        type="com.myapps.recipeApp.Recipe"/>
</data>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.myapp.recipeApp.RecipeActivity"
    tools:showIn="@layout/activity_recipe">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/r_source"
        android:textStyle="bold"
        android:text="@{recipe.source}"
        android:visibility="@{helper.presentationElementsVisible ? View.VISIBLE : View.GONE}" />
<!-- More TextViews here -->
<!-- Button is located in parret layout -->
</RelativeLayout>
</layout>

我强烈推荐阅读乔治·蒙特的关于 Android 数据绑定的帖子 https://medium.com/@georgemount007,它们非常有用。


为了解决这个问题,我将助手类扩展为基础可观察对象 https://developer.android.com/reference/android/databinding/BaseObservable.html如中所述文档 https://developer.android.com/topic/libraries/data-binding/index.html#observable_objects.

助手类

public class RecipeBinderHelper{
    private Boolean presentationElementsVisible;
    private Boolean timerElementsVisible;

    public RecipeBinderHelper(){
        this.presentationElementsVisible = true;
        this.timerElementsVisible = false;
    }
    public void setPresentationViewVisible(boolean presentationElementsVisible) {
        this.presentationElementsVisible = presentationElementsVisible;
        //Notifying change in the setter. 
        notifyPropertyChanged(BR.presentationElementsVisible);
    }
    //assigning Bindable annotation to the getter 
    @Bindable
    public Boolean getPresentationElementsVisible() {
        return presentationElementsVisible;
    }
    //getters and setters for private Boolean timerElementsVisible;
}

The binding.notifyChange();在 Activity 中是不必要的,可以删除。

现在,当单击按钮时,应用程序会根据需要删除 TextView。


一件奇怪的事情是 Android Studio(2.1.2,Ubuntu)给了我一个Cannot resolve symbol 'BR'警告,但应用程序会按预期编译和运行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Android 数据绑定动态切换布局元素的可见性。 的相关文章

  • Android 应用程序在后台运行时保存数据

    目前我正在开发 xmmp 客户端 当应用程序位于前台时 该客户端工作得很好 但由于事实上 当应用程序处于后台时 我在 Application 类中保存了大量数据 复杂的 ArrayList 字符串和布尔值作为公共静态 每个字段都被垃圾收集
  • 导航组件重复 NavArgs 的问题

    我有一个片段 class SomeFragment private val args by navArgs
  • Android SoundPool 堆限制

    我正在使用 SoundPool 加载多个声音剪辑并播放它们 据我所知 它的功能 100 正确 但在 load 调用期间 我的日志中充斥着以下内容 06 09 11 30 26 110 ERROR AudioCache 23363 Heap
  • 如何从 SQLite 获取记录总数

    我正在尝试从 Sqlite DB 获取行的总数 以下是我想要做的代码片段 我不知道我在这里做错了什么 public static int getTotalCount Context context Cursor c null try c g
  • Android libgdx 首选项丢失

    我在 Libgdx 引擎中创建了 Android 游戏 一段时间后 我注意到在某些应用程序杀手中杀死该应用程序后 或者如果我在 Android 设置中执行 强制关闭 操作 我保存到首选项中的游戏选项就会丢失 有办法防止这种情况吗 我从来没有
  • KitKat(及更低版本)设备上的 Android Material Design

    我将在我们学校开发一个 Android 应用程序作为一个项目 我想使用 Google 的新 Material Design 但我知道它仅适用于 Android L 设备 Jack Underwood 最近发布了名为 Today Calend
  • Android Studio 在编译时未检测到支持库

    由于 Android Studio 将成为 Android 开发的默认 IDE 因此我决定将现有项目迁移到 Android studio 中 项目结构似乎不同 我的项目中的文件夹层次结构如下 Complete Project gt idea
  • 在意图过滤器中使用多个操作时的默认值

    尝试理解 Android 中的意图和操作并查看文档 http developer android com guide topics intents intents filters html 但我一直看到的一件事是定义了多个操作的意图过滤器
  • 已经使用 AsyncTask doInBackground 但新数据未显示

    我使用 AsyncTask 创建一个聊天室来接收消息 因此它总是检查即将到来的消息并将其显示给客户端 但代码似乎无法按我希望的方式工作 在客户端只显示所有旧数据 新数据不显示 因为当我尝试从服务器发送消息时 新数据没有显示在客户端中 我对这
  • 应用程序未安装在 Android 模拟器上

    我正在 android Geocoder 中开发一个应用程序 当我运行该应用程序时 它会显示 2011 01 11 11 08 13 GeoTourProject 自动目标模式 使用现有模拟器 emulator 5554 运行兼容的 AVD
  • minHeight 有什么作用吗?

    在附图中 我希望按钮列与图像的高度相匹配 但我也希望按钮列有一个最小高度 它正确匹配图像的高度 但不遵守 minHeight 并且会使按钮向下滑动 我正在为按钮列设置这些属性
  • ComboBox DataBinding 导致 ArgumentException

    我的几个类对象 class Person public string Name get set public string Sex get set public int Age get set public override string
  • ROOM迁移过程中如何处理索引信息

    CODE Entity tableName UserRepo indices Index value id unique true public class GitHubRepo PrimaryKey autoGenerate true p
  • MediaCodec 创建输入表面

    我想使用 MediaCodec 将 Surface 编码为 H 264 使用 API 18 有一种方法可以通过调用 createInputSurface 然后在该表面上绘图来对表面中的内容进行编码 我在 createInputSurface
  • 检查 Android 手机上的方向

    如何查看Android手机是横屏还是竖屏 当前配置用于确定要检索的资源 可从资源中获取Configuration object getResources getConfiguration orientation 您可以通过查看其值来检查方向
  • 调节麦克风录音音量

    我们正在尝试调整录音时的音量级别 麦克风似乎非常敏感 会接收到很多静电 我们查看了 setVolumeControlStream 但找不到传入其中来控制麦克风的流 将您的音频源设置为 MIC using MediaRecorder Audi
  • 下载后从谷歌照片库检索图像

    我正在发起从图库中获取照片的意图 当我在图库中使用 Nexus 谷歌照片应用程序时 一切正常 但如果图像不在手机上 在 Google Photos 在线服务上 它会为我下载 选择图像后 我将图像发送到另一个活动进行裁剪 但在下载的情况下 发
  • Android - 将 ImageView 保存到具有全分辨率图像的文件

    我将图像放入 ImageView 中 并实现了多点触控来调整 ImageView 中的图像大小和移动图像 现在我需要将调整大小的图像保存到图像文件中 我已经尝试过 getDrawingCache 但该图像具有 ImageView 的大小 我
  • Android中webview的截图方法

    我在 webview 中的 html5 canvas 上画了一些线 并尝试使用下面的代码截取 webview 的屏幕截图 WebView webView WebView findViewById R id webview webView s
  • 在 Android 中,如何将字符串从 Activity 传递到 Service?

    任何人都可以告诉如何将字符串或整数从活动传递到服务 我试图传递一个整数 setpossition 4 但它不需要 启动时总是需要 0 Service 我不知道为什么我不能通过使用 Service 实例从 Activity 进行操作 publ

随机推荐