【问题标题】:Recyclerview is null through whole lifecycleRecyclerview 在整个生命周期中为空
【发布时间】:2019-09-01 11:55:33
【问题描述】:

我遇到了一个让我发疯的问题,我在网上搜索了几个小时,但找不到解决方案。当我将新数据添加到列表时,我想在我的 recyclerview 中的第一个视图上设置动画。但我不能,因为 recyclerview 是空的。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    orientation = getResources().getConfiguration().orientation;

    model = ViewModelProviders.of(getActivity()).get(ViewModelAdvices.class);
    model.getAdvices().observe(this, new Observer <List <Advice>>() {

        //Update recyclerview automatically when data is changed
        @Override
        public void onChanged(List <Advice> advices) {
            filtered_advices_list.clear();
            filtered_advices_list.addAll(advices);
            adapter_recycler_view.notifyDataSetChanged();

        }
    });
}

@Override
public void onResume() {
    super.onResume();
    Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.test_item);
    View v = recycler_view.getChildAt(0);
    v.startAnimation(animation);

}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.show_advices_fragment, container, false);

    setupLayoutDifferences(view);

    recycler_view = (RecyclerView) view.findViewById(R.id.recycler_view);
    layout_manager = new LinearLayoutManager(getContext());
    recycler_view.setLayoutManager(layout_manager);
    adapter_recycler_view = new AdapterRV(filtered_advices_list);
    recycler_view.setAdapter(adapter_recycler_view);

 spinner_1 = (Spinner) view.findViewById(R.id.spinner_1);
    adapter_spinner_1 = ArrayAdapter.createFromResource(view.getContext(), R.array.categories, android.R.layout.simple_spinner_item);
    adapter_spinner_1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner_1.setAdapter(adapter_spinner_1);

    spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView <?> parent, View view, int position, long id) {
            String category = spinner_1.getItemAtPosition(spinner_1.getSelectedItemPosition()).toString();
            model.setCategory(category);
        }
        @Override
        public void onNothingSelected(AdapterView <?> parent) { }
    });

    return view;
    }
} 

show_advices_fragment

    <LinearLayout 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"
        android:orientation="vertical"
        android:background="@color/colorBlueGreen"
        android:paddingBottom="6dp">



    <Spinner
            android:id="@+id/spinner_1"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:backgroundTint="@color/colorBlack" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom">

            <Button
                android:id="@+id/button_add_activity"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginTop="6dp"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:visibility="gone"
                android:text="@string/button_add_activity" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/button_add_activity"
                android:background="@color/colorLightGrey"
                android:scrollbars="vertical"
                />

        </RelativeLayout>

    </LinearLayout>

list_item_activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="@color/colorWhite"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:weightSum="3">

<TextView
    android:id="@+id/text_view_advice"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border"
    android:textColor="@color/colorPrimary"
    android:paddingRight="4dp"
    android:layout_weight="1"
    android:text="TextView" />

<TextView
    android:id="@+id/text_view_author"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorGrey"
    android:layout_weight="2"
    android:gravity="center"
    android:text="TextView" />

 </LinearLayout>

还有test_item

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime">

    <translate
        android:interpolator="@android:anim/decelerate_interpolator"
        android:fromXDelta="100%p"
        android:toXDelta="0"
        />

    <alpha
        android:fromAlpha="0.5"
        android:toAlpha="1"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        />

</set>

在 onResume 中,我认为我处于最后一个生命周期中,并且 recyclerview 已经在 onCreateView 中构建。我想在我到达 onResume 之前,recyclerview 的构建并没有完成,但是我该如何解决这个问题呢? 如果我在片段已经加载时用鼠标单击来制作动画,它可以工作,但当我切换片段并且 recyclerview 正在重新构建时则不行。

【问题讨论】:

  • 显示你的布局文件
  • 我为我的动画创建了一个线程,如果我的睡眠时间超过 200 毫秒,它就会起作用。可能是我的 ViewModel 和 Livedata 导致了问题。
  • 它是你的 onResume 方法。 onResume 总是在所有方法之前首先调用。如果你想从 onResume 方法做动画,那么只需将所有 recyclerview 设置代码也放在简历上。否则在回收站设置后将您的动画代码移动到 onCreateView 。你可以把if(recycler_view!=null) 然后做动画以避免崩溃。如果动画有效,它还会告诉您回收站视图是否已初始化。

标签: java android


【解决方案1】:

试试这个

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orientation = getResources().getConfiguration().orientation;

        model = ViewModelProviders.of(getActivity()).get(ViewModelAdvices.class);
        model.getAdvices().observe(this, new Observer<List<Advice>>() {

            //Update recyclerview automatically when data is changed
            @Override
            public void onChanged(List<Advice> advices) {
                filtered_advices_list.clear();
                filtered_advices_list.addAll(advices);

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.test_item);
        View v = recycler_view.getChildAt(0);
        v.startAnimation(animation);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.show_advices_fragment, container, false);

        setupLayoutDifferences(view);

        recycler_view = (RecyclerView) view.findViewById(R.id.recycler_view);
        layout_manager = new LinearLayoutManager(getContext());
        recycler_view.setLayoutManager(layout_manager);
        populateAdapter();


        spinner_1 = (Spinner) view.findViewById(R.id.spinner_1);
        adapter_spinner_1 = ArrayAdapter.createFromResource(view.getContext(), R.array.categories, android.R.layout.simple_spinner_item);
        adapter_spinner_1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_1.setAdapter(adapter_spinner_1);

        spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String category = spinner_1.getItemAtPosition(spinner_1.getSelectedItemPosition()).toString();
                model.setCategory(category);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        if (adapter_recycler_view != null){
            adapter_recycler_view.notifyDataSetChanged();
        }

        return view;
    }

    private void populateAdapter() {
        adapter_recycler_view = new AdapterRV(filtered_advices_list);
        recycler_view.setAdapter(adapter_recycler_view);
    }

【讨论】:

    【解决方案2】:

    您不能在 Fragment 中依赖 onResume(),因为在某些 Android 版本上它不是 100% 在 onCreateView() 之后调用的(更多详细信息请参见 Fragment onResume() & onPause() is not called on backstack)。所以,你的片段布局创建可能还没有完成。

    您可以等到 RecyclerView 用OnGlobalLayoutListener 完成所有项目的充气,然后显示第一个项目的动画:

    recycler_view.getViewTreeObserver()
                 .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                     @Override
                    public void onGlobalLayout() {
    
                      // show the animation
                      Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.test_item);
                      View v = recycler_view.getChildAt(0);
                      v.startAnimation(animation);
    
                      // remove listener so that this won't be called multiple time.
                      recycler_view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }); 
    

    【讨论】:

      【解决方案3】:

      感谢您尝试帮助我。问题是我的应用程序可能不是组织得最好的,所以在我的 recyclerview 完成它从 ViewModel 获得的列表之前,一切都会运行。但是在单独的线程上做动画就像一个魅力,然后我也可以完全控制动画。

      if(action.equals("addData")) {
      
                  Thread thread = new Thread() {
                      @Override
                      public void run() {
                          try {
      
                              boolean recycler_view_loading = true;
      
                              while(recycler_view_loading ) {
                                  sleep(250);
      
                                  if (recycler_view.getChildAt(0) != null) {
      
                                      Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.item_animation_side);
                                      View v = recycler_view.getChildAt(0);
                                      v.startAnimation(animation);
                                      recycler_view_loading  = false;
                                  }
                              }
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                      }
                  };
                  thread.start();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 2018-09-11
        • 2013-04-06
        • 1970-01-01
        相关资源
        最近更新 更多