Showing posts with label ListView. Show all posts
Showing posts with label ListView. Show all posts

How to Make a Context Menu for a ListView Item


1. In the MainActivity.java file, add an Action on Long Press on ListView ListItem

2. Inflate a Menu in the onCreateContextMenu method. Do not include the icon line in the XML file. A context menu does not support icons because they are simply a list of menu options that floats above the current activity.

3. Perform Action on Context Menu Selection

4. Compile and run!

Resources:

registerForContextMenu - Register View for a Context menu

Activity.registerForContextMenu was added in API Level
Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the View.OnCreateContextMenuListener on the view to this activity, soonCreateContextMenu(ContextMenu, View, ContextMenuInfo) will be called when it is time to show the context menu.
Parameters: view - The view that should show a context menu.
(Long click)

1. Bind ArrayAdapter to ListView

2. Add to end of onCreate method. After it is registered the ListView to be eligible to create a context menu.
registerForContextMenu registers a context menu.
getListView() returns a ListView object that is used for the registration. 

registerForContextMenu(getListView());

Resources:
http://developer.android.com/reference/android/app/Activity.html#registerForContextMenu(android.view.View)
http://thedevelopersinfo.wordpress.com/2009/11/06/using-context-menus-in-android/

onListItemClick - Set an Action for a ListItem Short Click

onListItemClick was added in API Level 1
This method will be called when an item in the list is selected. (short-pressed)

1. Bind ArrayAdapter to ListView

2. In the MainActivity.java file, add the following imports.

import android.widget.ListView;
import android.view.View;

3. Then add the following method after the onCreate method.
      //l: The ListView where the click happened
      //v: The item that was selected with the ListView
      //position: The position of the selected item in the list
      //id: The row ID of the item that was selected

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
}

4. Add your action in the onListItemClick method. To test it, add a toast with the below message.

"ListView: " + l + " View: " + v + " List Position: " + position + " RowID: " + id

5. Compile and run! Next Recommended Article: Create an Intent to Open a New Activity/Screen Resources: 
http://developer.android.com/reference/android/app/ListActivity.html#onListItemClick(android.widget.ListView, android.view.View, int, long)

Define your own ListView row item layout

Here is a simple ListView row item with a TextView.

1. Create a new xml filed named myrowitem.xml in the res\layout directory.

2. Open the myrowitem.xml and add the following line of code.

<?xml version="1.0" encoding="utf-8"?>

3. Add a TextView after the beginning tags above.

4. Add the below line immediately after the <TextView tag.

 xmlns:android="http://schemas.android.com/apk/res/android"

5. Compile and run!

Resources:

setListAdapter - Bind ArrayAdapter to ListView

setListAdapter was added in API Level 1
Provides the cursor for the list view. (ListActivity.setListAdapter)

1. Link a String Array to an ArrayAdapter named myArrayAdapter

2. Bind myArrayAdapter to the ListView by adding this line of code to the onCreate method.

setListAdapter(myArrayAdapter);

3. Compile and run!

Resources:
http://developer.android.com/reference/android/app/ListActivity.html#setListAdapter(android.widget.ListAdapter)


How to Display TextView instead of ListView when Empty

1. Extend the ListActivity class

2. In the main.xml file, add a TextView under the ListView.

3. The TextView must be named android:empty.

4. Set the TextView text to "No list Items"

Resources:




How to Extend the ListActivity class

ListActivity was added in API Level 1
An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item.
The class will inherit from the ListActivity class. The ListActivity requires that an adapter fill the contents of the list view.

1. Add a ListView to the main.xml file.

2. The ListView Name must be set to android:list

3. In the MainActivity.java file, add the below import.

import android.app.ListActivity;

4. Extend the class named ListActivity in your MainActivity class.

5. Compile and run!

Next Recommended Article: How to Display TextView instead of Listview when Empty

Resources:
http://developer.android.com/reference/android/app/ListActivity.html
http://xahlee.info/java-a-day/extend.html


android:id - Name a ListView

How to Name an ListView

android:id was added in API Level 1
This is a unique identifier name for the ListView, so you can refer to the ListView later in your project.

1. Add a ListView in your main.xml file.

2. In the main.xml file, add the code below.

  <ListView
        ...
       android:id = "@+id/myListView"
  />

3. The "+" character is required if you have not yet defined that id, if perhaps the element you reference is lower in the .xml file.

Otherwise you if it's already defined above (or included) then you can omit the "+" char:

4. Compile and run!

Next Recommended Article: How to Extend the ListActivity class

Resources:
http://developer.android.com/reference/android/view/View.html#attr_android:id
http://developer.android.com/reference/android/R.attr.html#id
http://android-wtf.com/2012/11/difference-between-at-plus-id-and-at-id-in-android/
http://stackoverflow.com/questions/5025910/difference-between-id-and-id-in-android
http://stackoverflow.com/questions/5048586/can-you-set-tab-order-in-xml-layout

How to Add a ListView to XML

ListView was added in API Level 1

1. Create an Android project if you don't already have one.

2. Open your layout/main.xml file. Add this section of code between the <LinearLayout ....> and the ending </LinearLayout> tags.

<ListView
android:layout_height="match_parent"
android:layout_width="match_parent">
</ListView>

3. Compile and run!

Next Recommended Article: android:id - Name a ListView

Remove/Delete ListView Item using ActionBar Button

How to Remove/Delete ListView Item using ActionBar Button, Step-By-Step

1.  Add a  ListView.

2. Add an Action Bar.

3. Add a variable to save the ListView Item position to your class.

public class MainActivity extends Activity{

int intListViewItemPosition = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {

4. Add this method to the end of your class. This will Remove selected item from ListView and Refresh/Update a ListView after adding or deleting Item to List, and uses a Toast.

public void removeListViewItem() {
if (intListViewItemPosition != -1) {
myList.remove(intListViewItemPosition);
myArrayAdapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
} else {
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
5. Add the below bolded line of code to the onOptionsItemSelected method

@Override
public boolean onOptionsItemSelected(MenuItem item) { //needs import android.view.MenuItem;
//super.onOptionsItemSelected(item);
switch (item.getItemId()) {

case R.id.menu_delete:
removeListViewItem();
return true;

6. Compile and run!


Other Resources:

setOnItemLongClickListener - Do Action on ListView Item LongClick, without extending ListActivity

How to Do an Action on ListView Item LongClick, without extending ListActivity

1. Add a ListView.

2. Open the MainActivity.java file and add these to the import section.

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;


3. Add the below section of code to the onCreate method.

myListView.setOnItemLongClickListener(new OnItemLongClickListener() {
     public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
              
//.....
              // Example, Display Toast of Position

              Toast.makeText(getApplicationContext(), " " + position , Toast.LENGTH_LONG).show();
              // Other Example action items:
              // Remove Selected Item from ListView

             return true;
    }
});


4. Compile and run!


Remove selected item from ListView

How to Remove (Delete) the selected Item from ListView, Step-By-Step

1. If you don't already have an Android project, create an Android project.

2. Add Action Item on ListView Item Click.

3. Open MainActivity.java and add the below bolded line

 myListView.setOnItemClickListener(new OnItemClickListener() {
    @Override public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
        MyList.remove(position);
      }
});

4. Compile and run!

5. This above will delete the item from the list, but will not refresh the ListView. To Refresh the ListView see, Update ListView after Deleting Item from List.

setOnItemClickListener - Do Action on ListView Item Click, without extendingListActivity

How to Do Action on ListView Item Click, without extending ListActivity

1. Add a ListView.

2. Open the MainActivity.java file and add these to the import section.

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;


3. Add the below section of code to the onCreate method.

myListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {

// Do action item here

//.....
                // Example, Display Toast of Position
                Toast.makeText(getApplicationContext(), " " + position , Toast.LENGTH_LONG).show();

                // Other example action items

                // Remove Selected Item from ListView

}

});

4. Compile and run!


Add a ListView

How to Add a ListView, Step-By-Step


There are two main types of ListViews, Static and Dynamic. Choose the one you'd like to create.

A Static ListView is a ListView where you will not be adding new items to the list at runtime.

A Dynamic ListView is a ListView where you will most likely be adding new items/changing items to the list at runtime.


Add a Dynamic ListView, Step-By-Step

How to Add a Dynamic ListView to your Android Project, Step-By-Step

After each step you should be able to compile and test, with no errors.

A "Dynamic ListView" is a ListView where items can be added.
A "Static ListView" is a ListView where the items in the ListView will not be changed.

1. Create a List with an ArrayList.

2. Link your ArrayAdapter to the ListView named myListView.

3. Compile and run!

Next Recommended Article: Do Action on ListView Item Click


Refresh/Update a ListView after adding or deleting Item to List

How to Update a ListView after adding or deleting an Item to a List, Step-By-Step

1. If you don't already have an Android project, create a new project.

2. Add a Dynamic ListView to your Android project.

3. Open your MainActivity.java file and add the below line below.

myListView.invalidateViews();

4. Compile and run!


Add a Basic ListView


1. Add a ListView to XML

2. Set android:id="@+id/myListView" in the ListView.

3. Now open the MainActivity.java file and add the below import to the imports section.

import android.widget.ListView;

4. Add the line: ListView myListView between the public class and the onCreate method.
Defining the myListView variable here will make this available throughout the whole class.

public class MainActivity extends ListActivity {

ListView myListView;

public void onCreate(Bundle savedInstanceState) {


5. Add the bolded code below in the OnCreate method after setContentView and before the end of the method }. This code will link your editText in your main.xml file to the editText in code.

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

6. Compile and run!

How to Add a Static ListView to your Android Project

A "Static ListView" meaning that the items in the ListView will not be changed. For a ListView that you'd like to add items to, see "Dynamic ListView".

1. Add a Basic ListView.

2. Add an array of items and name it arrayTasks.
For testing, make the list "Task 1", Task 2", Task 3", "Task 4", "Task 5"

3. Create an ArrayAdapter named myAdapter.

4. Link your ArrayAdapter to your Array.

5. Link your ArrayAdapter to the ListView named myListView.

6. Compile and run!

setAdapter - How to Link an ArrayAdapter to a ListView without extending ListActivity


1. Add the basic ListView.

2. Add an ArrayAdapter.

3. Link the ArrayAdapter to the ListView by adding this bolded line of code to the onCreate method in the MainActivity.java file.

myListView.setAdapter(myArrayAdapter);

4. Compile and run!

Solution for: Your content must have a ListView whose id attribute is 'android.R.id.list'


Problem: 

W/dalvikvm(17155): threadid=1: thread exiting with uncaught exception (group=0x40a351f8) E/AndroidRuntime(17155): FATAL EXCEPTION: main
E/AndroidRuntime(17155): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.akp.ToDoList/com.akp.ToDoList.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Solution:
1. Make sure the android:id line is as displayed below.

<ListView
  android:id="@android:id/list"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >
</ListView>


2. Test project.