Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Add a Selection List when using AppCompatActivity

Author: Daniel Fowler
Published? false -- FormatLanguage: W

Problem:

Your App needs the use a list but the Activity uses AppCompatActivity.

Solution:

Creating new screen classes in Studio sees them extend AppCompatActivity, in this case instead of using the Android ListActivity class a ListView is declared and assigned.

Discussion:

Open the App that needs a list selection screen, (alternatively see Start a Second Screen from the First for a starting point). Select the app folder in the Project explorer, use the File or context (normally right-click) menu. Select New then XML and Values XML File. Set Values File Name to coffeelist, click Finish, the file is created in the res/values folder as coffeelist.xml. Define a list as shown below (or use your own).

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="coffeeMenu">
        <item>Filter</item>
        <item>Americano</item>
        <item>Latte</item>
        <item>Expresso</item>
        <item>Cappucino</item>
        <item>Mocha</item>
        <item>Skinny Latte</item>
        <item>Expresso Corretto</item>
    </string-array>    
</resources>

The strings in this list are added to the R class to be accessed via a call to getResources. A ListView in the second screen will hold the strings. Open the second screen layout (activity_main2.xml if using the second screen example) and delete the TextView. Drop a ListView onto the screen. The Screen2 layout XML should resemble:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.helloworld.Main2Activity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

The App is displaying a simple list and Android has predefined list item definitions for such lists in android.R.layout with names such as simple_list_item_1, simple_list_item_2, simple_list_item_single_choice and others. See the full list in the documentation at [1]. Here simple_list_item_1 is used in the ListView. The Main2Activity.java class that loads the list entries and links them to the ListView via an ArrayAdapter.

package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Main2Activity extends AppCompatActivity {
    ListView coffeeList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        String[] coffeeChoices = getResources().getStringArray(R.array.coffeeMenu);
        coffeeList = (ListView) findViewById(R.id.listView);
        coffeeList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,coffeeChoices));
        coffeeList.setOnItemClickListener(new returnClickedItem());
    }
    class returnClickedItem implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String item = (String) parent.getItemAtPosition(position);
            Intent data = new Intent();
            data.putExtra("Order",item);
            setResult(RESULT_OK, data);
            finish();
        }
    }
}

The MainActivity.java starts the list screen and displays the selected item in a Toast:

package com.example.helloworld;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(new handleButton());
    }
    class handleButton implements View.OnClickListener {
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            startActivityForResult(intent, 0);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null && data.hasExtra("Order"))
            Toast.makeText(this, data.getStringExtra("Order") + " ordered.", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Nothing ordered!", Toast.LENGTH_LONG).show();
    }
}

See Also:

[1]

No records found.