Android DataBinding

时间:2017-02-04 03:24:01

标签: java android android-databinding

我正在尝试Android的数据绑定。我的应用程序正在调用API并将结果存储在对象模型中。我想在活动中显示模型的内容。我的API调用是通过单击按钮进行的​​。代码如下:

public class MainActivity extends AppCompatActivity {

private static final String apiKey = "somekey";
APIInterface apiService = null;
EditText editText;
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    apiService = APIClient.getClient().create(APIInterface.class);

    button = (Button) findViewById(R.id.button);
    editText = (EditText) findViewById(R.id.edit_text);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Result", "Inside onclick");
            String text = editText.getText().toString();
            Call<APIResultModel> call = apiService.getSearchResult(text, apiKey);
            Log.d("Result", "Before enqueue");
            call.enqueue(new Callback<APIResultModel>() {
                @Override
                public void onResponse(Call<APIResultModel> call, Response<APIResultModel> response) {
                    if (response.body().results != null) {
                        List<ProductModel> productModelList = response.body().results;
                        if (productModelList != null && productModelList.size() > 0) {
                            final ProductModel productModel = productModelList.get(0);
                            ActivityMainBinding binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
                            binding.setProduct(productModel);
                        }
                    }
                }

                @Override
                public void onFailure(Call<APIResultModel> call, Throwable t) {

                }
            });
            Log.d("Result", "After enqueue")
        }
    });

}
}

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">
<data>
    <variable
        name="product"
        type="com.mvvm.prakh.mvvmarchitecture.models.ProductModel" />
</data>

<RelativeLayout
    android:id="@+id/activity_main"
    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"
    tools:context="com.mvvm.prakh.mvvmarchitecture.MainActivity">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edit_text"
        android:layout_marginTop="8dp"
        android:text="Submit" />

    <TextView
        android:id="@+id/brand_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_marginTop="8dp"
        android:text="@{product.brandName}"
        android:hint="Brand name comes here" />

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/brand_name"
        android:layout_marginTop="8dp"
        android:text="@{product.productName}"
        android:hint="Product name comes here" />
</RelativeLayout>

我的模型如下:

package com.mvvm.prakh.mvvmarchitecture.models;

import android.databinding.BaseObservable;
import android.databinding.Bindable;

import com.android.databinding.library.baseAdapters.BR;
import com.google.gson.annotations.SerializedName;

public class ProductModel extends BaseObservable{
@SerializedName("brandName")
public String brandName;
@SerializedName("productName")
public String productName;

public ProductModel(String brandName, String productName) {
    this.brandName = brandName;
    this.productName = productName;
}

@Bindable
public String getBrandName() {
    return brandName;
}

public void setBrandName(String brandName) {
    this.brandName = brandName;
    notifyPropertyChanged(BR.brandName);
}

@Bindable
public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
    notifyPropertyChanged(BR.productName);
}
}

我在onClick()内放了一个Log.d语句,在第一次点击时它给出了输出但是对于后续的点击我没有得到输出。在我使用数据绑定填充字段后,似乎禁用了点击。

Logcat输出:

02-04 14:53:30.040 16778-16778/com.mvvm.prakh.mvvmarchitecture D/Result: Inside on click
02-04 14:53:30.135 16778-16778/com.mvvm.prakh.mvvmarchitecture D/Result: Before enqueue
02-04 14:53:30.151 16778-16778/com.mvvm.prakh.mvvmarchitecture D/Result: After enqueue

因此,点击按钮,我可以看到由于API而填充的数据,但是点击按钮后它会变得无法响应。我在这里缺少一些重置条件以允许再次单击按钮吗?

3 个答案:

答案 0 :(得分:0)

考虑到Android数据绑定,您的代码有几个问题。所有你应该在onCreate()的开头设置绑定并从那时开始使用。如果您没有引用它,则可以再次使用DataBindingUtil找到它。无需findViewById()或重置onResponse()中的布局。

DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main)

这会创建您的视图的新实例,而不是您之后设置的这些实例。相反,你应该像下面这样实现它。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
    apiService = APIClient.getClient().create(APIInterface.class);

    binding.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String text = binding.editText.getText().toString();
            Call<APIResultModel> call = apiService.getSearchResult(text, apiKey);
            call.enqueue(new Callback<APIResultModel>() {
                @Override
                public void onResponse(Call<APIResultModel> call, Response<APIResultModel> response) {
                    if (response.body().results != null) {
                        List<ProductModel> productModelList = response.body().results;
                        if (productModelList != null && productModelList.size() > 0) {
                            binding.setProduct(productModelList.get(0));
                        }
                    }
                }

                @Override
                public void onFailure(Call<APIResultModel> call, Throwable t) {
                }
            });
        }
    });
}

答案 1 :(得分:0)

调用DataBindingUtil.setContentView后,将重置onclicklistener。 这是我的数据绑定演示项目,希望对您有所帮助。 https://github.com/LenaYan/AndroidMVVM

答案 2 :(得分:0)

您需要稍微更改一下代码

public class MainActivity extends AppCompatActivity {
private static final String apiKey = "somekey";
APIInterface apiService = null;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(MainActivity.this,
R.layout.activity_main);
apiService = APIClient.getClient().create(APIInterface.class); 
binding.button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("Result", "Inside onclick");
        String text = editText.getText().toString();
        Call<APIResultModel> call = apiService.getSearchResult(text, apiKey);
        Log.d("Result", "Before enqueue");
        call.enqueue(new Callback<APIResultModel>() {
        @Override
        public void onResponse(Call<APIResultModel> call, Response<APIResultModel> response) {
                if (response.body().results != null) {
                    List<ProductModel> productModelList = response.body().results;
                    if (productModelList != null && productModelList.size() > 0) {
                        final ProductModel productModel = productModelList.get(0);
                         binding.setProduct(productModel);
                    }
                }
            }
            @Override
            public void onFailure(Call<APIResultModel> call, Throwable t) {
            }
        });
        Log.d("Result", "After enqueue")
    }
});
}
}    

在pojo的setter中放置NotifyChanges()而不是notifyPropertyChanged(int fieldId)。  Difference you can find from the link

和此链接中的教程enter link description here