ViewBinding не работает во втором экране [ошибка: невозможно найти импорт символа com.example.demoapp.databinding.DragAndDropBinding] - PullRequest
1 голос
/ 06 марта 2020

В основном у меня есть приложение с двумя экранами. ScreenOne и ScreenTwo. На первом экране я имею в виду, что в MainActivity viewBinding работает нормально. Но при нажатии на перкулярную кнопку он будет перенаправлен на второй экран. Теперь есть проблема. ошибка массажа -

error: cannot find symbol import com.example.demoapp.databinding.DragAndDropBinding;

Но на первом экране все работает нормально.

MainActivity [FirstScreen]

//Working Fine
package com.example.demoapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.example.demoapp.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.dragOnly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), DragActivity.class);
                v.getContext().startActivity(intent);
            }

        });
    }
}

ActivityMain. xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:orientation="vertical"
        android:layout_centerVertical="true">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/dragAndDrop"
            android:text="Drag and Drop"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Drag"
            android:id="@+id/dragOnly"/>

    </LinearLayout>

</RelativeLayout>

и DragAndDropActivity [Second Screen]

//Showing error for import com.example.demoapp.databinding.DragAndDropBinding;
package com.example.demoapp;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.demoapp.databinding.ActivityMainBinding;
import com.example.demoapp.databinding.DragAndDropBinding; //Error 

public class DragActivity extends AppCompatActivity {
    TextView textView;
    DragAndDropBinding binding;
    float xPosition, yPosition, xPrevious, yPrevious;
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drag_and_drop);
        textView = findViewById(R.id.dragButton);
        textView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int point = event.getActionMasked();

                switch (point) {
                    case MotionEvent.ACTION_DOWN:

                    case MotionEvent.ACTION_UP:
                        xPrevious = event.getX();
                        yPrevious = event.getY();
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        float dx = event.getX() - xPrevious;
                        float dy = event.getY() - yPrevious;

                        xPosition += dx;
                        yPosition += dy;

                        v.setX(xPosition - v.getWidth());
                        v.setY(yPosition - v.getHeight());

                        return true;

                    default:
                        return false;
                }

            }
        });
    }
}

DragAndDrop. xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Drag Me any Where"
        android:textSize="25sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/dragButton"
        android:background="#056"
        android:padding="8dp"
        android:textColor="#FFF"/>

</RelativeLayout>

build.gradle [Приложение]

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.demoapp"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    viewBinding {
        enabled = true
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Android Studio версии 3.6.1 и плагин Gradle classpath 'com.android.tools.build:gradle:3.6.1'

1 Ответ

0 голосов
/ 07 марта 2020

Я вижу, что вы на самом деле не используете ViewBinding во втором упражнении. Вы просто импортируете сгенерированный класс. Proguard скрывает неиспользуемые классы во время выполнения и думает, что вы не используете свой сгенерированный класс привязки представления (что верно, вы просто импортируете его.), Поэтому используйте его, как вы использовали в первом действии. Это будет работать.

...