Не работает прокрутка RecyclerView в макете, расширенном от базовой активности - PullRequest
0 голосов
/ 07 мая 2019

Мне нужна помощь с моим приложением для Android.Проблема, с которой я столкнулся, заключается в том, что я создал базовое действие, управляющее компоновкой ящика и панелью инструментов.Когда я расширяю его в действии для Relative Layout и вложенного Recycle View, у меня возникает проблема, что я не могу прокрутить его (но, когда действие начинается, я могу уловить момент и сделать это, но один раз).Другая ситуация - я открыл приложение, не расширяя базовую активность в своей активности для RecycleView, и оно работает нормально.

RecyclerView:

<?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"
    tools:context=".EntryList"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:id="@+id/entry_list">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:padding="4dp"
    android:scrollbars="vertical"
    app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

</RelativeLayout>

Основная активность (Drawer):

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

Панель инструментов, включенная в ящик:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/coordinator_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorWhite"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@drawable/gradient_color"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <FrameLayout
            android:id="@+id/activity_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

Базовая активность:

public abstract class BaseActivity extends AppCompatActivity {

    protected Context context;
    protected Toolbar toolbar;
    private DrawerLayout drawer;
    private ProgressBar loadingProgressBar;
    private NavigationView navigationView;
    private ActionBarDrawerToggle toggle;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        context = BaseActivity.this;
        setContentView(R.layout.activity_main);
    }

    @Override
    public void setContentView(int layoutResID) {
        DrawerLayout fullView = (DrawerLayout)getLayoutInflater().inflate(R.layout.activity_main, null);
        FrameLayout activityContainer = fullView.findViewById(R.id.activity_content);
        getLayoutInflater().inflate(layoutResID, activityContainer, true);

        super.setContentView(fullView);
        initToolBar();
    }

    private void initToolBar() {
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        setUpNavigation();
        toggle.syncState();
    }

    private void setUpNavigation() {
        drawer = findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(BaseActivity.this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar == null) {
            throw new NullPointerException("ActionBar is null");
        }
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);

        navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // Handle navigation view item clicks here.

                if (item.isChecked())
                    item.setChecked(false);
                else
                    item.setChecked(true);

                drawer.closeDrawers();

                Intent intent;
                switch (item.getItemId()) {
                    case R.id.nav_home:
                        intent = new Intent(BaseActivity.this, EntryList.class);
                        startActivity(intent);
                        return true;
                }

                return false;
            }
        });
        toggle.syncState();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (toggle.onOptionsItemSelected(item))
            return true;

        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

Адаптер:

public class EntryListAdapter extends RecyclerView.Adapter<EntryListAdapter.EntryListViewHolder> {

    private List<ExampleEntryItem> items;

    public static class EntryListViewHolder extends RecyclerView.ViewHolder {

        private TextView specieNameRuTextView;
        private TextView entryDateTextView;
        private TextView specieNameLatTextView;
        private TextView entryPlaceTextView;

        public EntryListViewHolder(@NonNull View itemView) {
            super(itemView);
            specieNameRuTextView = itemView.findViewById(R.id.specie_name_ru);
            entryDateTextView = itemView.findViewById(R.id.entry_date);
            specieNameLatTextView = itemView.findViewById(R.id.specie_name_lat);
            entryPlaceTextView = itemView.findViewById(R.id.entry_place);
        }
    }

    public EntryListAdapter(List<ExampleEntryItem> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public EntryListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.example_entry_item, parent, false);
        return new EntryListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull EntryListViewHolder entryListViewHolder, int position) {
        ExampleEntryItem item = this.items.get(position); // TODO: 06.05.2019 test for null
        entryListViewHolder.entryPlaceTextView.setText(item.getEntryPlace());
        entryListViewHolder.entryDateTextView.setText(item.getEntryDate());
        entryListViewHolder.specieNameRuTextView.setText(item.getSpecieNameRu());
        entryListViewHolder.specieNameLatTextView.setText(item.getSpecieNameLat());
    }

    @Override
    public int getItemCount() {
        return this.items.size();
    }

Класс управления RecycleView:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entry_list_content_main);

    List<ExampleEntryItem> items = new ArrayList<>();
    adding items...

    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    RecyclerView.Adapter adapter = new EntryListAdapter(items);
    adapter.notifyDataSetChanged();
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

}

Спасибо всем, кто мне поможет

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Я решил проблему.Я заменяю свою логику для повторного просмотра в фрагментах, и в основном меняю то, что я делаю, - в макете с панелью приложений я заменил <include layout="@layout/content"/> на внешнюю часть AppBarLayout и изменил строку:

android:layout_height="match_parent"
android:background="@color/colorWhite"

на эту:

android:layout_height="wrap_content"
0 голосов
/ 07 мая 2019

Сначала нужно удалить

adapter.notifyDataSetChanged()

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

...