привязка данных не привязывает данные с XML в Android - PullRequest
0 голосов
/ 06 ноября 2019

хочу реализовать привязку данных. Я реализовал код, данные поступают из API, но они не связаны с XML и не показывают никаких ошибок. Поэтому я не понимаю, в чем проблема .. Пожалуйста, помогите мне.

Мой код

content_policy_info.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="policyinfo"
            type="com.exlservice.lifeprov1.service.model.GetPolicyInfoResponse" />

        <variable
            name="surrenderquote"
            type="com.exlservice.lifeprov1.service.model.SurrenderQuoteResponse" />
    </data>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/c1"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".view.ui.PolicyInfo"
    tools:showIn="@layout/app_bar_policy_info">
    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:background="#223d50"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:background="@drawable/policy_prime_info_bg"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp"
                    android:orientation="horizontal">

                    <TextView
                        android:layout_width="0dp"
                        android:layout_marginLeft="5dp"
                        android:layout_height="wrap_content"
                        android:text="@{policyInfo.ProductId}"
                        android:textColor="#76c6db"
                        android:layout_weight="1"
                        android:typeface="serif"
                        android:textStyle="bold"
                        android:id="@+id/id_fc_first_key"/>
                    <TextView
                        android:layout_width="0dp"
                        android:textColor="#76c6db"
                        android:textStyle="bold"
                        android:typeface="serif"
                        android:layout_height="wrap_content"
                        android:text="@{policyInfo.Contract}"
                        android:layout_weight="1"
                        android:id="@+id/id_fc_second_key"/>

                </LinearLayout>
           </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>
</layout>

Policyinfo.java

public class PolicyInfo extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
APIInterface apiInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding= DataBindingUtil.setContentView(this,R.layout.activity_policy_info);
    Intent intent = getIntent();
    String sCompanyCode = intent.getStringExtra("CompanyCode");
    String sPolicyNumber = intent.getStringExtra("PolicyNumber");
    String sWayPoint = intent.getStringExtra("WayPoint");
    Log.e("onCreate: ",sCompanyCode+"   "+sPolicyNumber );
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String currentTime = sdf.format(new Date());
    SurrenderQuoteInput surrenderQuoteInput = new SurrenderQuoteInput();
    surrenderQuoteInput.setCoderID("TRN7");
    surrenderQuoteInput.setCompanyCode("01");   
    PolicyDetailsReq policyDetailsReq= new PolicyDetailsReq();
    policyDetailsReq.setCoderID("TRN7");

    getPolicyInfoRequest.setPolicyDetailsReq(policyDetailsReq);

    PolicyInfoViewModel.Factory factory = new PolicyInfoViewModel.Factory(
            **getApplication(),getPolicyInfoRequest,surrenderQuoteRequest);
    PolicyInfoViewModel viewModel =
            ViewModelProviders.of(this,factory).get(PolicyInfoViewModel.class);
    **observeViewModel**(viewModel);**

    // show it
    pd.show();
    DrawerLayout drawer =  findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView =  findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}
private void **observeViewModel**(final PolicyInfoViewModel viewModel) {
    // Update the list when the data changes
    viewModel.getPolicyInfoResponsetObservable().observe(this, new Observer<GetPolicyInfoResponse>() 
{
        @Override
        public void onChanged(@Nullable GetPolicyInfoResponse getPolicyInfoResponse) {
            if(getPolicyInfoResponse!=null) {
                viewModel.setPolicyInfoResult(getPolicyInfoResponse);
                binding.setPolicyinfo(getPolicyInfoResponse);
            }

        }

    });
}

Этот код предназначен для работы с панелью навигации, где все мои компоненты находятся в content_policy_info.xml. Пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 06 ноября 2019

Привязка данных является ОЧЕНЬ полезным инструментом и может сэкономить много рабочего времени, если все сделано правильно. Я действительно рекомендую прочитать это руководство , прежде чем пытаться реализовать что-то самостоятельно. Здесь я просто выделю основные шаги в настройке привязки данных

  1. Убедитесь, что в вашем приложении включена привязка данных: В своем приложении gradle добавьте

    dataBinding { enabled = true }

  2. Создайте привязку, специфичную для вашего xml-файла:

    ContentPolicyInfoBinding binding = DataBindingUtil.setContentView(this,R.layout.content_policy_info);

(Возможно, вы допустили ошибку, надувая Activity_policy_infoвместо этого?

Установите параметры привязки один раз как ObservablFields, если эти параметры должны со временем измениться

ObservablField<GetPolicyInfoResponse> policyInfoField = new ObservablField(); ... binding.policyinfo = policyInfoField;

Изменить XML для соответствия:

<import type="com.exlservice.lifeprov1.service.model.GetPolicyInfoResponse"/> <variable name="policyinfo" type="android.databinding.ObservableField&lt;GetPolicyInfoResponse&gt;"/>

Обновлять policyInfoField при поступлении нового policyInfo

policyInfoField.set(getPolicyInfoResponse)


Но более предпочтительно использоватьмодель представления, установите ее поля как привязываемые. Это позволяет обновлять вид, просто меняя поля модели.

...