Я получаю сообщение об ошибке при использовании librery привязки данных Android
Я успешно завершил работу над одним макетом.
но я создал новый макет и добавил тег <layout> в новые .xml и Build->clean project, а затем получил сообщение об ошибке
* What went wrong: Execution failed for task ':app:mergeDebugResources'.> Error: java.lang.ArrayIndexOutOfBoundsException
мой уровень модуля build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "codingwithmitch.com.databindinggettingstarted"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
Gradle wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-
all.zip
Gradle свойство
org.gradle.jvmargs=-Xmx1536m
android.enableExperimentalFeatureDatabinding=true
android.databinding.enableV2=true
MainActivity.java
public class MainActivity extends AppCompatActivity implements IMainActivity {
//DataBinding
ActivityMainBinding mBinding;
//Var
private Product mProduct;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
Products mProducts = new Products();
mProduct = mProducts.PRODUCTS[10];
mBinding.setProduct(mProduct);
mBinding.setQuantity(1);
mBinding.setIMainActivity(this);
mBinding.setTestImageUrl(String.valueOf(mProduct.getImage()));
}
@Override
public void inflateQuantityDialog() {
ChooseQuantityDialog dialog = new ChooseQuantityDialog();
dialog.show(getSupportFragmentManager(), getString(R.string.dialog_choose_quantity));
}
@Override
public void setQuantity(int quantity) {
mBinding.setQuantity(quantity);
}
@Override
public void addToCart() {
Toast.makeText(this, "Added to cart", Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<?xml version = "1.0" encoding = "utf-8"?>
<layout xmlns:app = "http://schemas.android.com/apk/res-auto">
<data>
<import type = "codingwithmitch.com.databindinggettingstarted.util.StringUtil" />
<import type = "codingwithmitch.com.databindinggettingstarted.util.BigDecimalUtil" />
<import type = "android.view.View" />
<variable
name = "product"
type = "codingwithmitch.com.databindinggettingstarted.models.Product" />
<variable
name = "quantity"
type = "int" />
<variable
name = "iMainActivity"
type = "codingwithmitch.com.databindinggettingstarted.interfaces.IMainActivity" />
<variable
name = "testImageUrl"
type = "String" />
</data>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:background = "@color/White">
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:padding = "10dp"
android:background = "@color/White">
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginRight = "10dp"
android:layout_marginEnd = "10dp"
android:layout_marginTop = "5dp">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "10sp"
android:textColor = "@color/DarkGrey"
android:text = "@{StringUtil.convertIntToString(product.num_ratings)}"
android:id = "@+id/num_ratings"
android:layout_alignParentEnd = "true"
android:layout_alignParentRight = "true"
android:layout_centerVertical = "true" />
<RatingBar
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
style = "?attr/ratingBarStyleSmall"
android:theme = "@style/RatingBar"
android:scaleX = "1.2"
android:scaleY = "1.2"
android:numStars = "5"
android:rating = "@{BigDecimalUtil.getFloat(product.rating)}"
android:id = "@+id/rating"
android:isIndicator = "true"
android:layout_toLeftOf = "@+id/num_ratings"
android:layout_marginRight = "10dp"
android:layout_centerVertical = "true" />
</RelativeLayout>
<TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/title"
android:textColor = "@color/Black"
android:text = "@{product.title}"
android:textSize = "14sp"
android:layout_marginTop = "5dp" />
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "200dp"
android:layout_marginTop = "10dp">
<ImageView
app:imageUrl = "@{product.image}"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:scaleType = "fitCenter"
android:layout_centerHorizontal = "true"
android:layout_centerVertical = "true"
android:id = "@+id/image" />
</RelativeLayout>
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "18dp"
android:layout_marginTop = "15dp"
android:orientation = "horizontal">
<ImageView
android:layout_width = "14sp"
android:layout_height = "14sp"
android:src = "@drawable/ic_dollor_sign_red" />
<TextView
android:id = "@+id/txtPrice"
android:visibility = "gone"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@{product.hasSalePrice() ? BigDecimalUtil.getValue(product.sale_price) : BigDecimalUtil.getValue(product.price)}"
android:textColor = "@color/red2"
android:textSize = "16sp" />
<TextView
android:id = "@+id/original_price"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginLeft = "10dp"
android:background = "@drawable/strike_through"
android:text = "@{BigDecimalUtil.getValue(product.price)}"
android:textColor = "@color/DarkGrey"
android:textSize = "10sp"
android:visibility = "@{product.hasSalePrice()? View.VISIBLE: View.GONE}" />
</LinearLayout>
<RelativeLayout
android:onClick = "@{()-> iMainActivity.inflateQuantityDialog()}"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:padding = "10dp"
android:background = "@drawable/grey_rounded_button"
android:layout_marginTop = "13dp"
android:id = "@+id/quantity_button">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "12sp"
android:textColor = "@color/Black"
android:text = "@{StringUtil.getQuantityString(quantity)}"
android:id = "@+id/quantity" />
<ImageView
android:layout_width = "14dp"
android:layout_height = "15dp"
android:layout_centerVertical = "true"
android:layout_marginLeft = "5dp"
android:layout_toRightOf = "@id/quantity"
android:src = "@drawable/ic_up_down_arrows" />
</RelativeLayout>
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:padding = "12dp"
android:layout_marginTop = "13dp"
android:background = "@drawable/orange_rounded_button"
android:onClick = "@{()->iMainActivity.addToCart()}"
android:id = "@+id/add_to_cart">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "14sp"
android:textColor = "@color/Black"
android:text = "Add to cart"
android:contentDescription = "@{product.title ?? product.description}"
android:id = "@+id/text_add_to_cart"
android:layout_centerHorizontal = "true"
android:layout_centerVertical = "true" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</layout>
IMainActivity public interface IMainActivity {
void inflateQuantityDialog();
void setQuantity(int quantity);
void addToCart();
}
этот код все в порядке, но я просто создаю файл .xml и добавляю тег <layout> и проект очистки, возникает ошибка.
<?xml version = "1.0" encoding = "utf-8"?>
<layout>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "170dp"
android:layout_height = "wrap_content"
android:background = "@drawable/grey_rounded_background">
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal"
android:background = "@drawable/grey_rounded_button"
android:padding = "5dp">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "16sp"
android:textColor = "@color/Black"
android:textStyle = "bold"
android:text = "@string/dialog_quantity_title"
android:layout_centerVertical = "true"
android:layout_marginLeft = "10dp" />
</RelativeLayout>
</LinearLayout>
</layout>
<layout> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "170dp" android:layout_height = "wrap_content" android:background = "@drawable/grey_rounded_background"> </LinearLayout> </layout>Никакого другого кода, я просто добавляю тег layout в новый xmlЕсть ли у вашего макета закрытый тег </layout>? Кстати, вы можете изменить вопрос (добавить макет и прочее)
хорошо, я отредактировал свой код, этот класс из gitub, он работает правильно. bt я не могу создать новый макет с привязкой данных.
Попробуйте использовать <layout xmlns:android = "http://schemas.android.com/apk/res/android"> вместо <layout> - проблема с разрешением пространства имен
это решает проблему?
Покажите код, в котором вы используете продукты.
@ConstOrVar Проблема не решена, могу ли я добавить только тег <layout> с пространством имен в файл xml, я просто делаю это, никаких других функций привязки данных, таких как activity_main.xml
@ Khemraj, я просто слежу за [github.com/mitchtabian/DataBindingGettingStarted] этот проект с [youtube.com/watch?v=v4XO_y3RErI] этот видеоурок. Он полностью очищен. Но я просто создаю новый XML-файл и добавляю теги привязки данных, он получает ошибку при очистке или восстановлении
У меня та же проблема. Кажется, это проблема с кодировкой, которая возникает только на компьютере с Windows. Вы запускаете тот же проект в Linux или Mac .. работает как шарм.
Спасибо за воспроизведение, я использую машину Windows. Как я могу решить эту проблему
Не могли бы вы разместить здесь новый макет
.xml?