Mahdi.Pishguy Mahdi.Pishguy - 5 months ago 17
Android Question

Android ListView setOnItemClickListener doesnt work (Resolved)

this simple code which has one listView into that, work fine, after move copy/paste that in other project,

setOnItemClickListener
doesnt work, all classes and
listview
id, activity layout are unique,why this listener doesnt work in project?

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ListView simple_list;
private ArrayList<SimpleModel> data;
private MyAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

data = new ArrayList<>();
simple_list = (ListView) findViewById(R.id.simple_list);

for (int i = 0; i <= 5; i++) {
data.add(new SimpleModel("Test " + i, "title " + i, "", ""));
}

adapter = new MyAdapter(this, data);
simple_list.setAdapter(adapter);
simple_list.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "ddddd " + i, Toast.LENGTH_SHORT).show();
}

public class MyAdapter extends ArrayAdapter<SimpleModel> {
public MyAdapter(Context context, ArrayList<SimpleModel> users) {
super(context, 0, users);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
SimpleModel data = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ewallet_items, parent, false);
}
TextView e_account_number = (TextView) convertView.findViewById(R.id.e_account_number);
e_account_number.setText(data.getAccount_number());
return convertView;
}
}

public class SimpleModel {
private String account_number;
private String title;
private String symbol;
private String amount;

public SimpleModel(String account_number, String title, String symbol, String amount) {
this.account_number = account_number;
this.title = title;
this.symbol = symbol;
this.amount = amount;
}
}
}


activity xml layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
android:id="@+id/simple_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@null"
android:divider="@null"/>
</RelativeLayout>


enter image description here

PROBLEM RESOLVED

parent listview items was clickable="true" , after remove that line, my problem resolved, Thanks to @The Curious Dev

Answer

If your ListView's row layout/item layout has some clickable elements then parent (row layout) will lose focus and OnItemClickListener wont work anymore.

If your row layout/item layout has any clickable item then you must add this to your parent layout :

android:descendantFocusability="blocksDescendants"

So the parent will get back its focus.