ListView / GridView not refreshing inside Fragment

200 Views Asked by At

The other elements of the fragment get updated, only listview and gridview that don't. I can see in Logs that the adapter's content is getting changed, but the views only refresh when I click on them or onResume().

I have already tried adapter.notifyDataSetChanged() and adapter.notifyDataSetInvalidated() in UIThread, listview.invalidateViews() and gridview.invalidateViews() and also requestLayout(), requestFocus() and performClick(), as they refresh when I touch on the view area.

I have also tried to detach/attach the fragment.

When I try to gridview.setAdapter again, the content gets blank and is shown updated when I click on the gridview area.

I'm using AndroidAnnotations.

@EActivity(R.layout.activity)
public class MyActivity extends AppCompatActivity {

@FragmentById
Fragment1 fragment1;

@FragmentById
Fragment2 fragment2;

void whenSomethingHappens() {
    fragment1.onChange();
    fragment2.onChange();
}
}

@EFragment(R.layout.fragment1)
public class Fragment1 extends Fragment {

@ViewById
GridView gridView;

@Bean
MyAdapter1 adapter1;

@AfterViews
void init() {
    gridView.setAdapter(adapter1);
}

void onChange() {
   adapter1.clear();
   adapter1.addAll(elements); // The elements are changed, but not the gridview
}
}

@EFragment(R.layout.fragment2)
public class Fragment2 extends Fragment {

@ViewById
ListView listView;

@Bean
MyAdapter2 adapter2;

@AfterViews
void init() {
    listView.setAdapter(adapter2);
}

void onChange() {
   adapter2.clear();
   adapter2.addAll(elements); // The elements are changed, but not the listView
}
}

@EBean
public class Adapter1 extends ArrayAdapter<Model1> {

@RootContext
Context context;

public Adapter1(Context context) {
    super(context, R.layout.model1_item);
}


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    Model1Item model1Item;
    if (convertView == null) {
        model1Item = Model1Item_.build(context);
    } else {
        model1Item = (Model1Item) convertView;
    }

    Model1 model1 = getItem(position);
    model1Item.bind(model1);
    return model1Item;
}
}

Adapter2 is the same as Adapter1 but with different models and items. The items are @ViewGroups just binding the model to the view elements.

EDIT: Right now, what's working best is requestFocusFromTouch(), but with a glitchy feel.

1

There are 1 best solutions below

0
On BEST ANSWER

Figure out that I wasn't calling onChange in all cases and also it wasn't running on the UIThread as expected. So basically the code change is:

@UiThread
void onChange() {
    adapter.clear();
    adapter.addAll(elements);
}