简体   繁体   中英

How to put a ListView inside a Fragment?

I'm trying to make a fragment with a listview inside it where I will put some data from api. I know how to do when I use activity.

I've create a base adapter and in my fragment I have something like this:

    Transactions_weekly transactions;

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

        listView = (ListView) view.findViewById(R.id.weekly_data_list);

        Intent intent = getIntent();
        transactions = (Transactions_weekly) intent.getSerializableExtra("transactions");
        Transaction_Weekly_Adapter adapter = new Transaction_Weekly_Adapter(this, transactions);
        ArrayAdapter<Transactions_weekly> arrayAdapter = new ArrayAdapter<>(
                Objects.requireNonNull(getActivity()),
                android.R.layout.simple_list_item_1,
                Collections.singletonList(transactions));
        listView.setAdapter(arrayAdapter);

        return  view;
}

The problem is in these two lines: Intent intent = getIntent(); saying cannot resolve method getIntent() and Transaction_Weekly_Adapter adapter = new Transaction_Weekly_Adapter(this, transactions);

Any help is appreciated !

Intent is held by your activity. Try Intent intent = getActivity().getIntent(); . This may fix your problem with the adapter variable too, but I notice that you never use that variable and create an arrayAdapter instead.

 1- getActivity().getIntent();

 2- Transaction_Weekly_Adapter adapter = new Transaction_Weekly_Adapter(getActivity(), transactions);

hope to help !

您可以通过使用容器活动来访问意图,因此您应该使用getActivity方法来访问意图

getActivity().getIntent();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM