我在布局中的 RecyclerView 中使用 databiding,如下所示:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/topup_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:items="@{viewModel.items}"
tools:listitem="@layout/list_item_content" />
Run Code Online (Sandbox Code Playgroud)
以及列表和绑定适配器,例如:
@BindingAdapter("app:items")
fun setItems(listView: RecyclerView, items: List<ListItem>?) {
items?.let {
(listView.adapter as MyListAdapter).submitList(items)
}
}
//------------------
class MyListAdapter() :
ListAdapter<ListItem, ViewHolder>(myListItemDiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(private val binding: ListItemContentBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: ListItem) {
binding.item = item
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder { …Run Code Online (Sandbox Code Playgroud) 我为 2 路数据绑定做了一个简单的 hello world,并且接缝工作完美(当在 editext 上写入时,textview 自动更新),但是在网上找到的所有代码(如官方文档)都有更多的代码和复杂性,例如https://developer.android。 com/主题/库/数据绑定/双向
这是我的代码:
public class MainActivity extends AppCompatActivity {
public String pippo;
public Boolean visible = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBindingUtil.setContentView(this, R.layout.activity_main);
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="pippo"
type="String" />
<variable
name="visible"
type="Boolean" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={pippo}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{pippo}"
android:visibility="@{visible ? android.view.View.VISIBLE: android.view.View.GONE}" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="@={visible}" />
</LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
特别是文档使用这个东西但接缝无用:
如何null通过数据绑定作为参数传递?
当它刚刚
android:onClick="@{() -> viewModel.switchFunction(null)}"
Run Code Online (Sandbox Code Playgroud)
我得到cannot find method switchFunction(java.lang.Object)例外。
我的 ViewModel 功能是
fun switchFunction(param: MyClass?) {
}
Run Code Online (Sandbox Code Playgroud) 在我的 Android 项目中,我使用视图绑定:
buildFeatures {
dataBinding = true
viewBinding = true
}
Run Code Online (Sandbox Code Playgroud)
理想情况下我只会使用dataBinding,但在这种情况下我总是需要使用标签
<layout ...> </layout>
Run Code Online (Sandbox Code Playgroud)
在 XML 布局中以使用它。这就是为什么我只在真正需要在 XML 中绑定数据的地方使用它。在其他情况下,我会使用viewBinding该插件,因为该插件'kotlin-android-extensions'已被弃用。一切正常,但是运行时出现以下问题Analyze -> Inspect code。完成后,会发现一些未使用的资源(在 下Android -> Lint -> Perfomance -> Unused resources),并且我会删除所有这些资源,因为我不需要它们,它还会删除为 XML 中的所有视图分配的 ID。但是,带有标签的 XML 中的 ID<layout ...> </layout>不会被删除。仅在使用时才会删除 ID viewBinding。
我不是专家,但我认为删除未使用的资源与 s 的 ID 没有任何关系View,并且这种情况不应该发生。
每次优化之后(意味着清理未使用的资源中的项目),我总是必须分配 ID,这是非常低效的,特别是当项目变得更大并且有更多的ViewID 时。
为什么会发生这种情况以及如何防止这种情况发生?
android android-studio android-databinding android-viewbinding
所以我不知道为什么,但我发现数据绑定类型不匹配。我在另一个应用程序中使用了完全相同的代码用于数据绑定,并且工作正常。 错误是:需要 ActivityMainBinding,找到:ViewDataBinding!
如果我只是删除对绑定的赋值,DataBinding.setContentView则会以红色突出显示:
没有足够的信息来推断类型变量 T
它总是有效,我不知道是否有一些更新或其他什么,但我不知道从哪里开始尝试解决这个问题。
MainActivity.kt
package com.pdstudios.practice
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.pdstudios.practice.databinding.ActivityMainBinding
import androidx.databinding.DataBindingUtil
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main) //PROBLEM HERE
setContentView(binding.root)
}
}
Run Code Online (Sandbox Code Playgroud)
构建.gradle(:应用程序)
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.pdstudios.practice"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures {
dataBinding = true
viewBinding = true …Run Code Online (Sandbox Code Playgroud) data-binding android kotlin android-studio android-databinding
在android的数据绑定语法中,无论如何都无需对表达式进行两次计算就可以对表达式的结果进行嵌套三元:
对于单一三元情况,我有以下几点:
android:textColor="@{stock.mStockDelta.compareTo(BigDecimal.ZERO) < 0 ?
@color/red : @color/green}"
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种方法可以仅使用xml为三个compareTo结果{-1,0,1}中的每一个设置颜色?
我一直试图在Spinner上设置一个双向绑定.
网上有很多这样的例子,这里有堆栈溢出,但它们都不适用于我.
它只是一个国家的微调器,我用这种方法为它定义了一个国家适配器:
@InverseBindingAdapter(attribute = "selectedCountry", event = "selectedCountryAttrChanged")
public static String bindCountryInverseAdapter(AppCompatSpinner pAppCompatSpinner) {
Object selectedItem = pAppCompatSpinner.getSelectedItem();
SpinnerAdapter adapter = pAppCompatSpinner.getAdapter();
if (adapter instanceof CountrySpinnerAdapter) {
return (String) selectedItem;
}
throw new UnsupportedOperationException("The adapter must be a CountrySpinnerAdapter");
}
@BindingAdapter(value = "selectedCountryAttrChanged", requireAll = false)
public static void bindCountryChanged(AppCompatSpinner pAppCompatSpinner, final InverseBindingListener newTextAttrChanged) {
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
newTextAttrChanged.onChange();
}
@Override
public void onNothingSelected(AdapterView<?> …Run Code Online (Sandbox Code Playgroud) 我有两个形状drawables,rounded_corners.xml和rounded_corners_red.xml,它们将分别用于显示有效的文本输入和无效的文本输入.
我希望在用户单击登录按钮时动态设置此drwable,以便在有效文本显示rounded_corners.xml且无效时显示rounded_corners_red.xml.
下面是我如何把它放在我的布局xml中.
<EditText android:id="@+id/et_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@={systemSettings.isValid ? @drawable/rounded_corners : @drawable/rounded_corners_red}"
android:text="@={systemSettings.serverIP, default=@string/ip_host}"
android:textColor="#000000" />
Run Code Online (Sandbox Code Playgroud)
我想基于我的模型类中定义的isValid observable varible动态应用drawable.我的代码编译没有错误.但它会给出运行时错误
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:The expression ((systemSettingsIsValidGet) ? (getDrawableFromResource(etIp, R.drawable.rounded_corners)) : (getDrawableFromResource(etIp, R.drawable.rounded_corners_red))) cannot cannot be inverted: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@429a75fd
file:D:xxx\app\src\main\res\layout\fragment_system_settings.xml
loc:92:47 - 92:128
****\ data binding error ****
Run Code Online (Sandbox Code Playgroud)
谁知道为什么会这样?谢谢.
android mvvm android-layout android-drawable android-databinding
我经历了许多与数据绑定相关的帖子,但没有找到解决我问题的方法.我已经创建了一个示例应用程序来学习数据绑定.
预期行为:我有一个edittext和textview.textview应该更新我在edittext中写的任何内容.
问题:我创建了一个Observable并将其链接到edittext和textview.在edittext中编写时,我的textview没有更新.我在这里做错了.请检查以下代码 -
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
activityMainBinding.setStudent(new Student("Rahul"));
activityMainBinding.executePendingBindings();
}
}
Run Code Online (Sandbox Code Playgroud)
activity_main.xml中
<?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>
<variable
name="student"
type="com.rahulchaurasia.databindingtest.Student"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.rahulchaurasia.databindingtest.MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="@{student.name}"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{student.name}"/>
</LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
Student.java
public class Student {
public ObservableField<String> name;
public Student(String n) {
name = new ObservableField<>(n);
}
} …Run Code Online (Sandbox Code Playgroud) 首先,这个问题不是'onClick'事件参数传递的情况。
我有一种方法与DateUtil类,如下所示:
public static String formatDate(long date) {
SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
dateFormat.setTimeZone(TimeZone.getDefault());
c.setTimeInMillis(date);
return dateFormat.format(c.getTimeInMillis());
}
Run Code Online (Sandbox Code Playgroud)
我的模型CommentEntity具有以下属性:
private int id;
private int productId;
private String text;
private Date postedAt;
Run Code Online (Sandbox Code Playgroud)
现在,在布局之一中,我将显示注释。
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable name="comment"
type="com.example.entity.CommentEntity"/>
<variable
name="dateUtil"
type="com.example.util.DateUtil"/>
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_alignParentRight="true"
android:layout_below="@id/item_comment_text"
//This line gives error for data binding
android:text="@{dateUtil.formatDate(comment.postedAt.time)}"/>
</layout>
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
在类long中找不到方法formatDate(com.example.util.DateUtil)
现在,对于相同的情况,如果我修改formatDate()方法,因为默认情况下它将花费当前时间,因此删除了数据绑定中传递的参数,它将可以完美地工作。
那么我是在做错什么还是错误?
请提供在数据绑定中将参数传递给方法的问题的解决方案。