问题
I am working in an Android app where I need to create onItemClick method,but I fail to do so. Below is the code where the onItemClick method does not work. Does anyone have idea why it does not work?
public class sample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.live_chat_screen);
mListview = (ListView) findViewById(R.id.mLiveview);
mListview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapters, View childView,int position, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(sample.this,"Item number : " + position + " clicked",Toast.LENGTH_LONG).show();
}
});
here is the xml:
<ListView
android:id="@+id/mLiveview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:scrollbars="vertical" >
</ListView>
Actually I have used two views in my app first is when the app is open and the another view is open while the listview is getting load.
Could somebody help me out.
回答1:
You are not setting your layout in your activity. First set your xml using setContentView() like this:
setContentView(R.layout.your_xml);
Then continue
mListview = (ListView) findViewById(R.id.mLiveview);
回答2:
Add this code to your layout then try again;
android:clickable="true"
android:focusable="true"
回答3:
Try this in your ListView
<ListView
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:scrollbars="vertical"
android:smoothScrollbar="true" />
If you are using custom ListView, such as using a check box, use
android:focusable="false"
android:focusableInTouchMode="false"
<CheckBox
android:id="@+id/chk_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:focusableInTouchMode="false" />
回答4:
The main thing you are forgetting is
setContentView(R.layout.activity_menus);
来源:https://stackoverflow.com/questions/18202496/listview-onitemclick-listener-is-not-working