How to call a function after activity is loaded

1.2k views Asked by At

I have an activity in android with a RecyclerView. I am trying to call getChildAt(i) on the RecyclerView in OnCreate but it returns null. I tried the same thing inside a button click listener that I created for testing and it returns the item fine. This must be due to the fact that the RecyclerView has not loaded its children at this point in the OnCreate and I need to access its first child while the activity is loading. Is there any form of listener that I can use to check once the activity is loaded and the RecyclerView's children are created without a manual button press as the activity is loaded? I am unable to find a suitable listener for the activity or the RecyclerView.

Here is my base code:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    mainRec = (RecyclerView) findViewById(R.id.cardList);
    mainRec.setHasFixedSize(true);

    lm = new LayoutManager(this);

    mainRec.setLayoutManager(lm);
    mainRecAdap = new HappyAdapter(db.getListData(), this);
    mainRec.setAdapter(mainRecAdap);

    //this is where I am trying to call getChildAt

}

@Override
protected void onPause()
{
    super.onPause();
    restoreState();
}

@Override
protected void onResume()
{
    super.onResume();
    restoreState();
}

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

private void restoreState()
{
    setToolbarColor(backgroundColour);
}


@Override
public void onBackPressed()
{
    super.onBackPressed();
    overridePendingTransition(R.anim.fade_forward, R.anim.right_slide_out);
}

@Override
protected int getLayoutResource()
{
    return R.layout.activity_list;
}

Thanks

1

There are 1 answers

2
Simas On BEST ANSWER

Why don't you use the specific attach listener that the RecyclerView has:

recyclerView.addOnChildAttachStateChangeListener(new RecyclerView
                .OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {

            }
        });