44. Events in ListView

Lecture



In this lesson:

- we consider ListView events: pressing - onItemClick, selection - onItemSelect, scrolling - onScroll

When interacting with the list, it may be necessary to handle events - clicking on an item and scrolling. Let's try to do it.

Let's create   project :

Project name : P0441_SimpleListEvents
Build Target : Android 2.3.3
Application name : SimpleListEvents
Package name : ru.startandroid.develop.p0441simplelistevents
Create Activity : MainActivity

Let's draw the main.xml screen:

  <? xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
android: layout_width = "fill_parent"
android: layout_height = "fill_parent"
android: orientation = "vertical">
<ListView
android: id = "@ + id / lvMain"
android: layout_width = "match_parent"
android: layout_height = "wrap_content">
</ Listview>
</ LinearLayout>

On the screen only ListView .

Just like in the last lesson, add a list of names to the resource res / values ​​/ strings.xml :

  <? xml version = "1.0" encoding = "utf-8"?> 
<resources>
<string name = "hello"> Hello World, MainActivity! </ string>
<string name = "app_name"> SimpleListEvents </ string>
<string-array name = "names">
<item> Ivan </ item>
<item> Marya </ item>
<item> Peter </ item>
<item> Anton </ item>
<item> Dasha </ item>
<item> Boris </ item>
<item> Kostya </ item>
<item> Igor </ item>
<item> Anna </ item>
<item> Denis </ item>
<item> Vadim </ item>
<item> Olga </ item>
<item> Sergey </ item>
</ string-array>
</ resources>

We write the code MainActivity.java :

package ru.startandroid.develop.p0441simplelistevents;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

final String LOG_TAG = "myLogs";

ListView lvMain;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

lvMain = (ListView) findViewById(R.id.lvMain);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.names, android.R.layout.simple_list_item_1);
lvMain.setAdapter(adapter);

lvMain.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
}
});

lvMain.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemSelect: position = " + position + ", id = "
+ id);
}

public void onNothingSelected(AdapterView<?> parent) {
Log.d(LOG_TAG, "itemSelect: nothing");
}
});

}
}

We look code. We find the screen elements, create and assign an adapter to the list. Next, we assign two event handlers to the list:

1) OnItemClickListener - handles clicking on a list item

Provides us with the onItemClick method (AdapterView <?> Parent, View view, int position, long id), where

parent - View-parent for the clicked item, in our case - ListView
view is the clicked item, in our case the TextView of android.R.layout.simple_list_item_1
position - the ordinal number of the item in the list
id - the identifier of the element

We will log the id and position for the element we clicked on.

2) OnItemSelectedListener - handles the selection of list items (not check, as in the previous lesson)

Provides us with the onItemSelected method is completely similar in parameters to the onItemClick method described above. I will not repeat.

There is also a method onNothingSelected - when the list loses the selection of an item and no item is selected.

All save and run the application.

We tap some element, for example - Peter. We look at the log:

itemClick: position = 2, id = 2

That's right. Because position is not counted from one, but from zero - Peter has position 2. (In our case, id is equal to position. I haven’t seen any id! = position, but surely they are)

Now spin the mouse wheel or press the keys up and down on the keyboard. It is visible that there is a visual selection of elements of the list.

And in the logs we see such records:

itemSelect: position = 2, id = 2
itemSelect: position = 3, id = 3
itemSelect: position = 4, id = 4
itemSelect: position = 5, id = 5
itemSelect: position = 4, id = 4
itemSelect: position = 3, id = 3
itemSelect: position = 2, id = 2

Those. handler fixes which item is selected . Frankly, I do not really understand how you can use this selection. But there is a handler for it and I decided to tell about it. Let it be.

Now click again on any item in the list, we see that the selection is gone. Logs:

itemSelect: nothing
itemClick: position = 3, id = 3

Nothing is selected and the item with position 3 is pressed.

Let's add another handler to the list:

lvMain.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Log.d(LOG_TAG, "scrollState = " + scrollState);
}

public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
Log.d(LOG_TAG, "scroll: firstVisibleItem = " + firstVisibleItem
+ ", visibleItemCount" + visibleItemCount
+ ", totalItemCount" + totalItemCount);
}
});

OnScrollListener - handles list scrolling.

Methods:

1) onScrollStateChanged (AbsListView view, int scrollState) - processing scroll states

view is a scrollable item, i.e. Listview
scrollState - list state. It can take three values:

SCROLL_STATE_IDLE = 0, the list has finished scrolling
SCROLL_STATE_TOUCH_SCROLL = 1, the list started scrolling
SCROLL_STATE_FLING = 2, the list is “rolled”, i.e. when scrolling released a finger and scrolling goes further "by inertia"

I logged the log output so that it does not interfere. A little later repent.

2) onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) - scroll processing

view - scrollable item
firstVisibleItem - the first visible item on the screen
visibleItemCount - how many points are visible on the screen
totalItemCount - how many items in the list

Moreover, for the firstVisibleItem and visibleItemCount parameters, the item is considered to be visible on the screen even if it is not fully visible.

All save and run.

Now drag the list back and forth with the cursor (as if with a finger) and see the logs. There are too many things displayed. I will not lay out here. But the principle is clear - the first visible item changes (firstVisibleItem) and the number of visible items (visibleItemCount) can change by one.

Now we comment out the output to the log in the onScroll method (so as not to spam us the log) and replicate in onScrollStateChanged .

lvMain.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
        Log.d(LOG_TAG, "scrollState = " + scrollState) ;
}

public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
        //Log.d(LOG_TAG, "scroll: firstVisibleItem = " + firstVisibleItem
// + ", visibleItemCount" + visibleItemCount
// + ", totalItemCount" + totalItemCount);
}
});

Save, run.

We grab the list, pull it back a little and let it go. We look at the log:

scrollState = 1
scrollState = 0

Two events worked out - the list started scrolling, the list finished scrolling.

Let's try to take a list, “roll” it and release.

scrollState = 1
scrollState = 2
scrollState = 0

We see three events - the scrolling has begun , the list is “ knocked out ”, the scrolling is over .

Full lesson code:

package ru.startandroid.develop.p0441simplelistevents;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

final String LOG_TAG = "myLogs";

ListView lvMain;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

lvMain = (ListView) findViewById(R.id.lvMain);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.names, android.R.layout.simple_list_item_1);
lvMain.setAdapter(adapter);

lvMain.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
}
});

lvMain.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemSelect: position = " + position + ", id = "
+ id);
}

public void onNothingSelected(AdapterView<?> parent) {
Log.d(LOG_TAG, "itemSelect: nothing");
}
});

lvMain.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.d(LOG_TAG, "scrollState = " + scrollState);
}

public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
Log.d(LOG_TAG, "scroll: firstVisibleItem = " + firstVisibleItem
+ ", visibleItemCount" + visibleItemCount
+ ", totalItemCount" + totalItemCount);
}
});

}
}


In the next lesson:

- build an ExpandableListView tree list

avatar
28.4.2020 8:20

Делаю по вашему уроку, хочу по нажатию на элементы списка, открывать следующие страницы, естественно, то что написано ниже даже говнокодом не назовешь)
каким способом лучше реализовать это?
я читал, что для отдельной страницы нужно отдельное активити, и т.д. но если можно хотелось бы пример кода, как это сделать для одного элемента списка, а дальше я уж как нибудь сам) на андроиде новичек, как и в java.(

avatar
28.4.2020 8:20

lvMain.setOnItemClickListener(new OnItemClickListener()
public void onItemClick(AdapterView ? parent, View view,
int position, long id)


switch ((int)id)
case 0:

setContentView(R.layout.test_layout);

break;
case 1:

setContentView(R.layout.test_layout2);
break;

avatar
28.4.2020 8:21

Вся нужная Вам информация находится в уроках 21 - 25.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Mobile Programming (Android IOs)

Terms: Mobile Programming (Android IOs)