问题
I wrote a layout xml like below.
But the Kotlin compiler says Cannot resolve symbol 'Int'
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<layout ...>
<data>
<import type="androidx.databinding.ObservableArrayMap" />
<variable
name="myList"
type="ObservableArrayMap<Int,String>" />
</data>
<!-- ...... -->
</layout>
Is it possible to use kotlin builtins in android databinding xml?
回答1:
- Use java
Integer
instead of kotlinInt
. - You can not use characters <,> etc in XML. So use HTML entities.
like
ObservableArrayMap<Integer,String>
回答2:
You can add data binding simple way.
Configure your app to use the data binding:
Open the app/build.gradle, Then you have to add these line of code inside the android tags in gradle and sync project
dataBinding {
enabled = true
}
Layout and Binding Expression in Data Binding:
Open the layout (XML) file activity_main and replace the root with layout tag and place all tags inside to layout tags.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout>
<layout>
Replace the traditional setContentView() to DataBindingUtil.setContentView() in Activity:
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
}
}
Let’s us see how to data bind with Views and Widget using data binding
binding.tvName.setText("Monika Sharma");
binding.tvAddress.setText("251 mansarovar Jaipur | India ");
binding.tvFollowers.setText("240K");
binding.tvfollowing.setText("324K");
来源:https://stackoverflow.com/questions/53113356/how-to-use-kotlin-int-in-databinding