如何使片段中的Listview适配器工作

时间:2019-05-27 15:47:29

标签: java android android-listview

我正在使用带有listview的片段来显示Firebase数据库中的某些元素。但是适配器似乎无法正常工作。我跟踪了代码,一切看起来都很好。有人知道我在哪里错误吗?

我在适配器上下文中尝试了getActivity()。getBaseContext()和getContext(),但它也不起作用

public class ListFragment extends Fragment implements View.OnClickListener{

    private RecyclerView rcv;
    private ListView lstvw;
    DatabaseReference ddbbr;

    public ListFragment() {
        // Required empty public constructor
    }


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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        lstvw = v.findViewById(R.id.lstvwlistamini);
        ddbbr = FirebaseDatabase.getInstance().getReference("juegos");
        ddbbr.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                ArrayAdapter<String> adapter;
                ArrayList<String> list = new ArrayList<String>();

                for (DataSnapshot datasnapshot: dataSnapshot.getChildren()) {

                    Juego juego =  datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    list.add(titulo);
                    Toast toast = Toast.makeText(getContext(),list.get(0).toString(),Toast.LENGTH_LONG);
                    toast.show();

                }
                adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list);
                lstvw.setAdapter(adapter);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

正如我所说,该应用程序不会崩溃并且界面可以正常工作,但是列表视图为空

1 个答案:

答案 0 :(得分:0)

当您返回Fragment的视图时,您正在膨胀一个新视图,在onCreateView函数的最后一行返回膨胀了的视图,请替换:

return inflater.inflate(R.layout.fragment_list, container, false);

与:

return v;