у меня проблема с привязкой данных в android studio - PullRequest
0 голосов
/ 31 января 2020

Я вдруг обнаружил, что мой переплет. <widget name> не работает. Затем я заметил, что выпадающий список эмулятора также не работает.

Я прилагаю скриншоты моей IDE для справки.

enter image description here enter image description here

Зависимости Gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.jakewharton:butterknife:10.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    implementation "androidx.appcompat:appcompat:1.1.0"
    implementation "androidx.appcompat:appcompat-resources:1.1.0"
    implementation "androidx.autofill:autofill:1.0.0"
    implementation "androidx.core:core:1.1.0"
    implementation 'com.google.android.material:material:1.0.0'

    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.google.firebase:firebase-database:19.2.0'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
}

основной код активности

    package com.example.myapplication.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.pojo.IncomeModel;
import com.example.myapplication.pojo.PaymentModel;
import com.example.myapplication.ui.adapter.IncomeListAdapter;
import com.example.myapplication.ui.adapter.PaymentsListAdapter;
import com.example.myapplication.ui.viewModel.IncomeViewModel;
import com.example.myapplication.ui.viewModel.PaymentViewModel;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    private static float totalPayment;
    private static float totalIncome;

    private static boolean paymentView = true;



    PaymentViewModel paymentViewModel;
    IncomeViewModel incomeViewModel;
    ViewDataBinding binding;
    PaymentsListAdapter adapterP;
    IncomeListAdapter adapterI;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setDataBindingAndObservers();
        setMenuItem();
        paymentRecyclerView();
        incomeRecyclerView();
        setPaymentRecycler();
        setTotalSettle();
        setFabClick();

    }


    private void setDataBindingAndObservers() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        paymentViewModel = new ViewModelProvider(this).get(PaymentViewModel.class);
        incomeViewModel = new ViewModelProvider(this).get(IncomeViewModel.class);

        paymentViewModel.paymentLiveList.observe(this,paymentModels -> onPaymentLiveListChange(paymentModels));
        incomeViewModel.incomLiveList.observe(this, incomeModels -> onIncomeLiveListChange(incomeModels));

        paymentViewModel.totalPayment.observe(this,aFloat -> onTotalPaymentChange(aFloat));
        incomeViewModel.totalIncome.observe(this, aFloat -> onTotalIncomeChange(aFloat));
    }

    private void setMenuItem() {
        setSupportActionBar(binding.toolbar);
        binding.toolbar.inflateMenu(R.menu.item_menu);
        binding.toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.item_switch :
                    switchItemClicked();
                    return true;
                default:
                    return false;
            }
        });
    }

    private void paymentRecyclerView() {
        adapterP = new PaymentsListAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void incomeRecyclerView() {
        adapterI = new IncomeListAdapter();
              binding.recyclerView.setAdapter(adapterI);
              binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void switchItemClicked() {
      if(paymentView) setIncomeRecycler();
      else setPaymentRecycler();
      invalidateOptionsMenu();
    }

    private void setPaymentRecycler() {
        binding.recyclerView.setAdapter(adapterP);
        paymentView = true;
    }

    private void setIncomeRecycler() {
        binding.recyclerView.setAdapter(adapterI);
        paymentView = false;
    }

    private void setTotalSettle() {
        binding.tvTotalSettle.setText(String.format("%s", totalIncome - totalPayment));
    }

    private void setFabClick() {
        binding.floatingActionButton.setOnClickListener(v -> { 
            if(paymentView)paymentViewModel.getPaymentList();
            else incomeViewModel.getIncomeList();
        });
    }




    private void onPaymentLiveListChange(ArrayList<PaymentModel> paymentModels) {
        adapterP.setPaymentList(paymentModels);
    }

    private void onIncomeLiveListChange(ArrayList<IncomeModel> incomeModels) {
        adapterI.setIncomeList(incomeModels);
    }

    private void onTotalPaymentChange(float aFloat) {
        totalPayment = aFloat;
        setTotalSettle();
    }

    private void onTotalIncomeChange(float aFloat) {
        totalIncome = aFloat;
        setTotalSettle();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.item_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.item_switch) switchItemClicked();
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.item_switch);
        if (paymentView) {
            item.setTitle(R.string.item_income);
        } else {
            item.setTitle(R.string.item_payments);
        }
        return super.onPrepareOptionsMenu(menu);
    }


}

деятельность_основная структура


<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

    </data>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/floatingActionButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="12dp"
            android:clickable="true"
            android:focusable="true"
            app:srcCompat="@android:drawable/ic_menu_add" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorPrimaryDark"
            android:paddingBottom="8dp"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
            app:layout_constraintBottom_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:foregroundTint="#2B2B2B">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsing"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
                app:layout_scrollInterpolator="@android:anim/decelerate_interpolator"
                app:toolbarId="@+id/toolbar">

                <androidx.cardview.widget.CardView
                    android:id="@+id/cardView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center|start"
                    android:layout_margin="4dp">

                    <androidx.appcompat.widget.Toolbar
                        android:id="@+id/toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        app:title="hi!">

                        <androidx.constraintlayout.widget.ConstraintLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent">

                            <TextView
                                android:id="@+id/tv_total_settle"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginStart="32dp"
                                android:layout_marginTop="8dp"
                                android:layout_marginBottom="8dp"
                                android:text="@string/tv_total_payment"
                                android:textSize="@dimen/font_dim_big"
                                app:layout_constraintBottom_toBottomOf="parent"
                                app:layout_constraintStart_toEndOf="@+id/tv_total"
                                app:layout_constraintTop_toTopOf="parent" />

                            <TextView
                                android:id="@+id/tv_total"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginStart="16dp"
                                android:layout_marginTop="8dp"
                                android:layout_marginBottom="8dp"
                                android:text="@string/tv_total"
                                android:textSize="@dimen/font_dim_big"
                                app:layout_constraintBottom_toBottomOf="parent"
                                app:layout_constraintStart_toStartOf="parent"
                                app:layout_constraintTop_toTopOf="parent" />
                        </androidx.constraintlayout.widget.ConstraintLayout>
                    </androidx.appcompat.widget.Toolbar>
                </androidx.cardview.widget.CardView>


            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>

edit:

1 - я попытался удалить макеты и теги данных и заново добавить их

2 - я попытался перестроить проект

1 Ответ

0 голосов
/ 01 февраля 2020

решено:)

эта строка, казалось, была отредактирована идеей так:

привязка ViewDataBinding;

но она должна быть такой

ActivityMainBinding binding;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...