我有一个listview,想要在这个片段中的每个项目上设置一个onClickListener,但是它不起作用。我也想在listview上设置一个contextMenu,但这也不起作用。
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
purchasedItemsView = inflater.inflate(R.layout.purchased_items_fragment , container, false);
db = new StoreDataBase(getActivity() , Consts.StoreDB.DB_NAME , Consts.StoreDB.DB_VERSION);
storeArrayList = new ArrayList<>();
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
adapter .notifyDataSetChanged();
registerForContextMenu(listView);
sendData(purchasedItemsView);
return purchasedItemsView;
}
private void sendData(View view){
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
listView = (ListView) view.findViewById(R.id.storeListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
}else{
}
}
答案 0 :(得分:0)
listview
完成一次后, 重新初始化onCreateView()
。因此,从sendData()
方法中删除这一行:
// remove this
listView = (ListView) view.findViewById(R.id.storeListView);
然后,您需要将此部分代码移到if
语句之外或onCreateView()
方法之内。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
答案 1 :(得分:0)
第1点: 看起来你的数组列表是空的,所以填写一些数据
storeArrayList = new ArrayList<>();
//-------------------------------------
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
if(names != null && names.length() > 0) {
storeArrayList.addAll(names);
}
}
//-------------------------------------
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
第2点:你不需要“notifyDataSetChanged();”在您设置适配器之后。
//adapter .notifyDataSetChanged();
第3点: 使用长按监听器显示上下文菜单
listView.setOnItemLongClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "long press clicked");
//show dialog or context menu dialog.
}
});
第4点: 注释sendData方法并直接使用onclick
//sendData(purchasedItemsView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
希望这会有所帮助。 投票 - 如果你喜欢它。