@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
listView=container.findViewById(R.id.listview);
// View view= inflater.inflate(R.layout.fragment_home_page, container, false);
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_home_page,null);
final HomePageListAdapter homePageListAdapter=new HomePageListAdapter(container.getContext(),productName,sku,type,profile,getLayoutInflater());
listView.setAdapter(homePageListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(),productName[position],Toast.LENGTH_SHORT).show();
}
});
return v;
}
java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView $ OnItemClickListener)' 在com.example.webcreta.ui.home.Home.HomePage.HomePageFragment.onCreateView(HomePageFragment.java:42)上的空对象引用上
答案 0 :(得分:2)
先膨胀视图然后初始化
尝试以下代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// View view= inflater.inflate(R.layout.fragment_home_page, container, false);
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_home_page,null);
listView=v.findViewById(R.id.listview);
final HomePageListAdapter homePageListAdapter=new HomePageListAdapter(container.getContext(),productName,sku,type,profile,getLayoutInflater());
listView.setAdapter(homePageListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(),productName[position],Toast.LENGTH_SHORT).show();
}
});
return v;
}
答案 1 :(得分:0)
尝试此代码
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
listView = view.findViewById(R.id.listview);
final HomePageListAdapter homePageListAdapter=new HomePageListAdapter(container.getContext(),productName,sku,type,profile,getLayoutInflater());
listView.setAdapter(homePageListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(),productName[position],Toast.LENGTH_SHORT).show();
}
});
return view;
}
希望对您有帮助