Как выполняется двусторонняя привязка данных в панели навигации? - PullRequest
0 голосов
/ 05 ноября 2019

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

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);

    pd = new ProgressDialog(PolicyInfo.this);
    //setContentView(R.layout.activity_policy_info);

    pref= getSharedPreferences("LoginDetail", 0);
    Toolbar toolbar =  findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Poilcy Info");
    apiInterface = APIClient.getClient().create(APIInterface.class);
    FloatingActionButton fab =  findViewById(R.id.fab);



    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    apiInterface = APIClient.getClient().create(APIInterface.class);

    PolicyInfoViewModel viewModel =
            ViewModelProviders.of(this,factory).get(PolicyInfoViewModel.class);
    **observeViewModel**(viewModel);
    pd.setTitle("Loading...");
    pd.setMessage("Please wait.");
    pd.setCancelable(false);
    // 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);
            }
           /* if (getLastAccessedDetailsResult != null) {
                getLastAccessedDetailsRes=getLastAccessedDetailsResult;
                viewModel.setLastAccessedDetailsResult(getLastAccessedDetailsResult);
                setupViewPager(viewPager);
            }*/
        }

    });
}

Выше ошибки, показывающей исключение приведения класса android.support.v7.widget.AppCompatTextView не может быть приведен к android.support.design.widget.NavigationView

Полная трассировка стека

2019-11-05 16: 28: 27.673 3019-3019 / com.exlservice.lifeprov1 E / AndroidRuntime: ИСКЛЮЧИТЕЛЬНОЕ ИСКЛЮЧЕНИЕ: основной Процесс: com.exlservice.lifeprov1, PID: 3019 java.lang.RuntimeException: Невозможно запустить действие ComponentInfo {com.exlservice.lifeprov1 / com.exlservice.lifeprov1. view.ui.PolicyInfo}: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView нельзя привести к android.support.design.widget.NavigationView в android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2817). на android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2892) на android.app.ActivityThread.-wrap11 (неизвестный источник: 0) на android.app.ActivityThread $ HhandleMessage (ActivityThread.java:1593) в android.os.Handler.dispatchMessage (Handler.java:105) в android.os.Looper.loop (Looper.java:164) в android.app.ActivityThread.main (ActivityThread.java): 6541) на java.lang.reflect.Method.invoke (собственный метод) на com.android.internal.os.Zygote $ MethodAndArgsCaller.run (Zygote.java:240) на com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Вызывается: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView не может быть приведен к android.support.design.widget.NavigationView в com.exlservice.lifeprov1.databinding.ActivityPolinding. ActivityPolicyInfoBindingImpl.java:30) в com.exlservice.lifeprov1.databinding.ActivityPolicyInfoBindingImpl. (ActivityPolicyInfoBindingImpl.java:27) в com.exlservice.lifeprov1.DataBinderMapperImpl.getDataBinder:mpDataDinderBinderMinderBinderMinderBinderMinderBinderMinderBinderMinderBinderMinderBinderMinderBinderMinderBinder.IdBMBBMergedDataBinderMapper.java:74) в android.databinding.DataBindingUtil.bind (DataBindingUtil.java: 199) в android.databinding.DataBindingUtil.bindToAddedViews (DataBindingUtil.java:327) в android.databinding.DataBindingUtil.setContentView (DataBindingUtil.java:306) в android.databinding.DataBindingUtil.setContentView (DataBindingUtil.jpg). на com.exlservice.lifeprov1.view.ui.PolicyInfo.onCreate (PolicyInfo.java:58) на android.app.Activity.performCreate (Activity.java:6975) на android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1213) в android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2770) в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2892) в android.app.ActivityThread.-wrap11 (неизвестный источник: 0) в android.app.ActivityThread $ H.handleMessage (ActivityThread.java:1593) на android.os.Handler.dispatchMessage (Handler.java:105) на android.os.Looper.loop (Looper.java:164) на android.app.ActivityThread. main (ActivityThread.java:6541) в java.lang.reflect.Method.invoke (собственный метод) в com.android.internal.os.Zygote $ MethodAndArgsCaller.run (Zygote.java:240) на com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

1 Ответ

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

Кажется, что вы пытаетесь инициализировать NavigationView с помощью AppCompatTextView

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

В PolicyInfo Строка активности 58 внутри метода onCreate ()

Попробуйте проверить, где вы используете этот идентификатор (R.id.nav_view) и правильно его инициализируйте

...