gpt4 book ai didi

java - 如何在fragment Activity 下填充自定义 ListView (扩展Fragment)

转载 作者:行者123 更新时间:2023-12-01 07:52:57 25 4
gpt4 key购买 nike

我想在 Fragment Activity 下添加一些项目的简单 ListView ,该 Activity 扩展了 Fragment 但不是 ListFragment

这是我的代码:

public class ProductListFragment extends Fragment {

String[] ibizzproducts=
{
"Attendance",
"GPS",
"CCTV"
"Website"
"Application"

};

ListView listView;


public static ProductListFragment newInstance(int sectionNumber) {
ProductListFragment fragment = new ProductListFragment();
Bundle args = new Bundle();
args.putInt(Constants.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

for(int i=0;i < ibizzproducts.length;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Products Here : " + ibizzproducts[i]);

aList.add(hm);
}

String[] from = { "Products Here" };

int[] to = { R.id.listView1};

View v = inflater.inflate(R.layout.fragment_product_list, container, false);

// ListView list = (ListView)v.findViewById(R.id.listView1);

listView = (ListView)v.findViewById(R.id.listView1);

SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.fragment_product_list, from, to);

listView.setAdapter(adapter);
return v;

如果我在onCreateView()中使用它,那么它会给我错误:

java.lang.IllegalStateException: android.widget.ListView is not a  view that can be bounds by this SimpleAdapter

我只想添加简单的 ListView ,这样如果我从抽屉导航中选择 Product ,它应该向我显示这个简单的产品项目列表。

请帮我解决这个问题。谢谢

最佳答案

这里:

listView.setAdapter(adapter);

listView 对象为 null,因为 getActivity().findViewById 用于从 fragment_product_list 布局访问 ListView,其中是Fragment的布局。

因为ListView的list对象是从fragment_product_list初始化的,它是从onCreateView方法返回的,所以用它来setAdapter 对于 ListView:

list.setAdapter(adapter);

关于java - 如何在fragment Activity 下填充自定义 ListView (扩展Fragment),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com