Example usage for android.widget ListView setAdapter

List of usage examples for android.widget ListView setAdapter

Introduction

In this page you can find the example usage for android.widget ListView setAdapter.

Prototype

@Override
public void setAdapter(ListAdapter adapter) 

Source Link

Document

Sets the data behind this ListView.

Usage

From source file:com.example.android.miwok.activity.FamilyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_list);//ww w .j  av a  2  s .  c  om

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("father", "p", R.drawable.family_father, R.raw.family_father));
    words.add(new Word("mother", "a", R.drawable.family_mother, R.raw.family_mother));
    words.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son));
    words.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
    words.add(new Word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
    words.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother,
            R.raw.family_younger_brother));
    words.add(new Word("older sister", "tee", R.drawable.family_older_sister, R.raw.family_older_sister));
    words.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister,
            R.raw.family_younger_sister));
    words.add(new Word("grandmother ", "ama", R.drawable.family_grandmother, R.raw.family_grandmother));
    words.add(new Word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));

    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(this, words);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) findViewById(R.id.list);
    listView.setBackgroundColor(Color.parseColor("#379237")); //<--this is another way to set the background color is it wasn't in colors.xml
    //listView.setBackgroundColor(R.color.category_family);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);

    //plays the audio for number one when any item in the list is clicked click
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //release current resources being used for media player if it currently exists
            //because we are about to play a different sound file.
            releaseMediaPlayer();

            //get the word located in the list that is at same position as the item clicked in the list
            Word currentWord = words.get(position);

            // Request audio focus for playback
            int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
                    // Use the music stream.
                    AudioManager.STREAM_MUSIC,
                    // Request temporary focus.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {

                //create the medial player with the audio file that is stored in the list for that word.
                mMediaPlayer = MediaPlayer.create(getApplicationContext(), currentWord.getmMiwokAudio());
                //play the file
                mMediaPlayer.start();

                //listener to stop and release the media player and resources being used
                // once the sounds has finished playing
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });
}

From source file:com.jesjimher.bicipalma.MesProperesActivity.java

/**
 *   Actualiza el listado de estaciones 
 *//*w  w w  .  jav  a2s .  co m*/
public void actualizarListado() {
    // Si no se han descargado las estaciones y hay ubicacin disponible, no hacer nada
    if ((estaciones.size() == 0) || (lBest == null))
        return;

    // Ocultar el dilogo de bsqueda de ubicacin si se estaba visualizando
    if (dRecuperaEst.isShowing())
        dRecuperaEst.dismiss();

    // Mirar si est activa la opcin de ocultar estaciones vacas
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean ocultarVacios = sharedPrefs.getBoolean("ocultarVaciosPref", false);

    // Calcular distancias desde la ubicacin actual hasta cada estacin, generando
    // un objeto Resultado
    ArrayList<ResultadoBusqueda> result = new ArrayList<ResultadoBusqueda>();
    Iterator<Estacion> i = estaciones.iterator();
    while (i.hasNext()) {
        Estacion e = (Estacion) i.next();
        Location aux = e.getLoc();
        Double dist = Double.valueOf(lBest.distanceTo(aux));
        if (!(ocultarVacios && (e.getBicisLibres() <= 0)))
            result.add(new ResultadoBusqueda(e, dist));
    }

    // Ordenar por distancia
    Collections.sort(result);

    // Mostrar
    ListView l = (ListView) this.findViewById(R.id.listado);
    l.setAdapter(new ResultadoAdapter(this, result));
}

From source file:com.arcgis.android.samples.localdata.localrasterdata.FileBrowserFragment.java

private void initializeFileListView() {
    ListView lView = (ListView) (getView().findViewById(R.id.fileListView));
    lView.setBackgroundColor(Color.LTGRAY);
    LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);//from ww  w  . j a v a  2  s  .  c o m
    lParam.setMargins(15, 5, 15, 5);
    lView.setAdapter(this.adapter);
    lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            chosenFile = fileList.get(position).file;
            final File sel = new File(path + "/" + chosenFile);
            if (sel.isDirectory()) {
                // Directory
                if (sel.canRead()) {
                    // Adds chosen directory to list
                    pathDirsList.add(chosenFile);
                    path = new File(sel + "");
                    loadFileList();
                    adapter.notifyDataSetChanged();
                    updateCurrentDirectoryTextView();
                } else {
                    showToast("Path does not exist or cannot be read");
                }
            } else {
                // File picked or an empty directory message clicked
                if (!mDirectoryShownIsEmpty) {
                    // show a popup menu to allow users to open a raster layer for
                    // different purpose including basemap layer, operational layer,
                    // elevation data source for BlendRenderer, or some combinations.
                    PopupMenu popupMenu = new PopupMenu(getActivity(), view);
                    popupMenu.inflate(R.menu.file_browser_popup_menu);
                    popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            switch (item.getItemId()) {
                            case R.id.menu_raster_base_layer:
                                returnFileFinishActivity(sel.getAbsolutePath(),
                                        RasterLayerAction.BASEMAP_LAYER);
                                break;
                            case R.id.menu_raster_operational_layer:
                                returnFileFinishActivity(sel.getAbsolutePath(),
                                        RasterLayerAction.OPERATIONAL_LAYER);
                                break;
                            case R.id.menu_raster_elevation_source:
                                returnFileFinishActivity(sel.getAbsolutePath(),
                                        RasterLayerAction.ELEVATION_SOURCE);
                                break;
                            case R.id.menu_raster_base_elevation:
                                returnFileFinishActivity(sel.getAbsolutePath(),
                                        RasterLayerAction.BASEMAP_LAYER_AND_ELEVATION_SOURCE);
                                break;
                            case R.id.menu_raster_operational_elevation:
                                returnFileFinishActivity(sel.getAbsolutePath(),
                                        RasterLayerAction.OPERATIONAL_LAYER_AND_ELEVATION_SOURCE);
                                break;
                            }
                            return true;
                        }
                    });
                    popupMenu.show();
                }
            }
        }
    });

}

From source file:com.facebook.samples.rps.FriendActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.friends_activity);

    FragmentManager fragmentManager = getSupportFragmentManager();
    friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_fragment);
    friendPickerFragment.setShowTitleBar(false);

    ListView friendActivityList = (ListView) findViewById(R.id.friend_activity_list);
    String[] mapColumnNames = { "date", "action" };
    int[] mapViewIds = { R.id.friend_action_date, R.id.friend_game_result };
    friendActivityAdapter = new SimpleCursorAdapter(this, R.layout.friend_activity_row, createEmptyCursor(),
            mapColumnNames, mapViewIds);
    friendActivityList.setAdapter(friendActivityAdapter);
    friendActivityProgressBar = (ProgressBar) findViewById(R.id.friend_activity_progress_bar);

    friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
        @Override//from  w w  w  . j a  v a 2 s .  co m
        public void onError(PickerFragment<?> fragment, FacebookException error) {
            FriendActivity.this.onError(error);
        }
    });
    friendPickerFragment.setUserId("me");
    friendPickerFragment.setMultiSelect(false);
    friendPickerFragment.setOnSelectionChangedListener(new PickerFragment.OnSelectionChangedListener() {
        @Override
        public void onSelectionChanged(PickerFragment<?> fragment) {
            FriendActivity.this.onFriendSelectionChanged();
        }
    });
    friendPickerFragment.setExtraFields(Arrays.asList(INSTALLED));
    friendPickerFragment.setFilter(new PickerFragment.GraphObjectFilter<GraphUser>() {
        @Override
        public boolean includeItem(GraphUser graphObject) {
            Boolean installed = graphObject.cast(GraphUserWithInstalled.class).getInstalled();
            return (installed != null) && installed.booleanValue();
        }
    });

    Button inviteButton = (Button) findViewById(R.id.invite_button);
    inviteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            WebDialog.RequestsDialogBuilder builder = new WebDialog.RequestsDialogBuilder(FriendActivity.this,
                    Session.getActiveSession()).setTitle(getString(R.string.invite_dialog_title))
                            .setMessage(getString(R.string.invite_dialog_message))
                            .setOnCompleteListener(new WebDialog.OnCompleteListener() {
                                @Override
                                public void onComplete(Bundle values, FacebookException error) {
                                    if (error != null) {
                                        Log.w(TAG, "Web dialog encountered an error.", error);
                                    } else {
                                        Log.i(TAG, "Web dialog complete: " + values);
                                    }
                                }
                            });
            if (friendId != null) {
                builder.setTo(friendId);
            }
            builder.build().show();
        }
    });
}

From source file:com.dsi.ant.antplus.pluginsampler.watchdownloader.Activity_WatchScanList.java

/** Called when the activity is first created. */
@Override//from w ww.  ja v a  2 s.  c o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_device_list);

    tv_status = (TextView) findViewById(R.id.textView_Status);

    deviceList_Display = new ArrayList<Map<String, String>>();
    adapter_deviceList_Display = new SimpleAdapter(this, deviceList_Display,
            android.R.layout.simple_list_item_2, new String[] { "title", "desc" },
            new int[] { android.R.id.text1, android.R.id.text2 });

    ListView listView_Devices = (ListView) findViewById(R.id.listView_deviceList);
    listView_Devices.setAdapter(adapter_deviceList_Display);

    //Set the list to download the data for the selected device and display it.
    listView_Devices.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
            if (!bDevicesInList || watchPcc == null)
                return;

            final CharSequence[] downloadOptions = { "All Activities", "New Activities",
                    "Wait For New Activities" };
            AlertDialog.Builder builder = new AlertDialog.Builder(Activity_WatchScanList.this);
            builder.setTitle("Download...");
            builder.setItems(downloadOptions, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int downloadSelection) {
                    antFsProgressDialog = new ProgressDialog(Activity_WatchScanList.this);
                    antFsProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    antFsProgressDialog.setMessage("Sending Request...");
                    antFsProgressDialog.setCancelable(false);
                    antFsProgressDialog.setIndeterminate(false);

                    fitFileList = new ArrayList<FitFile>();

                    if (downloadSelection == 0) // download all
                    {
                        if (watchPcc.requestDownloadAllActivities(deviceInfoArray[pos].getDeviceUUID(),
                                new DownloadActivitiesFinished(pos), new FileDownloadedReceiver(),
                                new AntFsUpdateReceiver())) {
                            antFsProgressDialog.show();
                        }

                    } else if (downloadSelection == 1) // download new
                    {
                        if (watchPcc.requestDownloadNewActivities(deviceInfoArray[pos].getDeviceUUID(),
                                new DownloadActivitiesFinished(pos), new FileDownloadedReceiver(),
                                new AntFsUpdateReceiver())) {
                            antFsProgressDialog.show();
                        }
                    } else if (downloadSelection == 2) {
                        boolean reqSubmitted = watchPcc.listenForNewActivities(
                                deviceInfoArray[pos].getDeviceUUID(),
                                new IDownloadActivitiesFinishedReceiver() {
                                    @Override
                                    public void onNewDownloadActivitiesFinished(AntFsRequestStatus status) {
                                        //Only received on cancel right now, only thing to do is cancel dialog, already taken care of below
                                    }
                                }, new FileDownloadedReceiver() {
                                    @Override
                                    public void onNewFitFileDownloaded(FitFile downloadedFitFile) {
                                        super.onNewFitFileDownloaded(downloadedFitFile);

                                        //Now show each file as we get it
                                        List<FitFile> newActivityOnly = new ArrayList<FitFile>(fitFileList);
                                        fitFileList.clear();
                                        final Dialog_WatchData dataDialog = new Dialog_WatchData(
                                                deviceInfoArray[pos], newActivityOnly);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                dataDialog.show(getSupportFragmentManager(), "DeviceData");
                                            }
                                        });
                                    }
                                });

                        //Once the listener is started we leave this dialog open until it is cancelled
                        //Note: Because the listener is an asynchronous process, you do not need to block the UI like the sample app does with this, you can leave it invisible to the user
                        if (reqSubmitted) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(Activity_WatchScanList.this);
                            LayoutInflater inflater = Activity_WatchScanList.this.getLayoutInflater();

                            // Inflate and set the layout for the dialog
                            // Pass null as the parent view because its going in the dialog layout
                            View detailsView = inflater.inflate(R.layout.dialog_progresswaiter, null);
                            TextView textView_status = (TextView) detailsView
                                    .findViewById(R.id.textView_Status);
                            textView_status.setText("Waiting for new activities on "
                                    + deviceInfoArray[pos].getDisplayName() + "...");
                            builder.setView(detailsView);
                            builder.setNegativeButton("Cancel", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //Let onCancelListener take care of business
                                    dialog.cancel();
                                }
                            });
                            builder.setOnCancelListener(new OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    if (watchPcc != null) {
                                        watchPcc.cancelListenForNewActivities(
                                                deviceInfoArray[pos].getDeviceUUID());
                                    }
                                }
                            });
                            AlertDialog waitDialog = builder.create();
                            waitDialog.show();
                        }
                    }
                }
            });

            AlertDialog alert = builder.create();
            alert.show();
        }
    });
    resetPcc();
}

From source file:com.example.meind.meinders_habittracker.MainActivity.java

@SuppressWarnings("StatementWithEmptyBody")
@Override/*  ww w .  ja  v a 2s. c  om*/
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        // Handle the camera action
    } else if (id == R.id.nav_history) {
        Intent intent2 = new Intent(this, History_page.class);
        startActivity(intent2);
    } else if (id == R.id.nav_reset) {
        //got from
        //http://www.tutorialspoint.com/android/android_alert_dialoges.htm

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure you want to delete all data?");

        alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                HabitListController.getHabitList().removeHabits();

                HabitListController.getHabitList().notifyListener();
                HabitListController.getHabitList().addListener(new Listener() {
                    @Override
                    public void update() {
                        //updating the list once it gets deleted
                        ListView listview = (ListView) findViewById(R.id.HabitList);
                        final ArrayList<Habit> habitsArrayList = HabitListController.getHabitList()
                                .getAllHabits();
                        final ArrayAdapter<Habit> HabitAdapter = new ArrayAdapter<Habit>(MainActivity.this,
                                android.R.layout.simple_list_item_1, habitsArrayList);
                        listview.setAdapter(HabitAdapter);

                        HabitAdapter.notifyDataSetChanged();
                    }
                });
                Toast.makeText(MainActivity.this, "All data has been deleted!", Toast.LENGTH_LONG).show();
            }
        });

        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do nothing
            }
        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

From source file:cl.smartcities.isci.transportinspector.adapters.dialogAdapters.IncomingBusesAdapter.java

private void setBusesList(String pBusStopCode, String pBusStopTitle) {
    Button backButton = (Button) this.alertDialog.findViewById(R.id.back_button);
    TextView titleCode = (TextView) this.alertDialog.findViewById(R.id.bus_stop_code);
    TextView titleName = (TextView) this.alertDialog.findViewById(R.id.bus_stop_title);
    AppCompatImageView visibilityIcon = (AppCompatImageView) this.alertDialog
            .findViewById(R.id.visibility_icon);

    setViewIcon(visibilityIcon);/*  www.java  2s  . c o m*/
    /* set title elements */
    backButton.setVisibility(View.INVISIBLE);
    backButton.setClickable(false);
    titleCode.setText(pBusStopCode);
    titleName.setText(pBusStopTitle);
    /* set AlertDialog content view*/
    ListView listView = this.alertDialog.getListView();
    IncomingBusesAdapter adapter = new IncomingBusesAdapter(this.context, this.services, busStop);
    adapter.setDialog(this.alertDialog);
    adapter.setVisibilityIcon(visibilityIcon);
    listView.setAdapter(adapter);
}

From source file:aerizostudios.com.cropshop.MainActivity.java

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

    fragmentManager = getSupportFragmentManager();
    initMenuFragment();/*  ww w.jav  a 2 s  .c om*/

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    toolbarText = (TextView) findViewById(R.id.toolbarText);

    //shared pref
    if (isFirstTime()) {
        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("res", 300);
        editor.commit();

    }

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
    quality = prefs.getInt("res", 300);

    Typeface billabong = Typeface.createFromAsset(getAssets(), "fonts/Billabong.ttf");

    toolbarText.setTypeface(billabong);

    cropButton = (FancyButton) findViewById(R.id.OpenPhotoButton);
    followButton = (FancyButton) findViewById(R.id.FollowButton);

    followButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("http://instagram.com/_u/crop__shop");
            Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);

            likeIng.setPackage("com.instagram.android");

            try {
                startActivity(likeIng);
            } catch (ActivityNotFoundException e) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://instagram.com/crop__shop")));
            }

        }
    });
    cropButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            startActivityForResult(GetImageFromGallery.getPickImageIntent(MainActivity.this), REQUEST_PICTURE);

        }
    });

    mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);

    mLayout.setTouchEnabled(true);
    mLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
        @Override
        public void onPanelSlide(View panel, float slideOffset) {
            if (mLayout != null) {
                if (mLayout.getAnchorPoint() == 1.0f) {
                    mLayout.setAnchorPoint(0.7f);
                    mLayout.setPanelState(SlidingUpPanelLayout.PanelState.ANCHORED);
                } else {
                    mLayout.setAnchorPoint(1.0f);
                    mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                }
            }
        }

        @Override
        public void onPanelExpanded(View panel) {
            getSupportActionBar().hide();
        }

        @Override
        public void onPanelCollapsed(View panel) {
            getSupportActionBar().show();
        }

        @Override
        public void onPanelAnchored(View panel) {
            getSupportActionBar().show();
        }

        @Override
        public void onPanelHidden(View panel) {

        }
    });

    final ListView friends = (ListView) findViewById(R.id.flipAbout);

    FlipSettings settings = new FlipSettings.Builder().defaultPage(1).build();
    friends.setAdapter(new FriendsAdapter(this, Utils.friends, settings));

}

From source file:de.electricdynamite.pasty.ClipboardFragment.java

@Override
public void onLoadFinished(Loader<PastyLoader.PastyResponse> loader, PastyLoader.PastyResponse response) {

    ProgressBar pbLoading = (ProgressBar) getSherlockActivity().findViewById(R.id.progressbar_downloading);
    pbLoading.setVisibility(View.GONE);
    pbLoading = null;//from  w  w w  .  ja  v a 2 s . c om

    mHelpTextBig.setTextColor(getResources().getColor(R.color.abs__primary_text_holo_light));
    mHelpTextBig.setBackgroundDrawable(mBackground);

    if (response.isFinal) {
        getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.FALSE);
        if (response.getResultSource() == PastyResponse.SOURCE_CACHE) {
            Toast.makeText(getSherlockActivity().getApplicationContext(),
                    getString(R.string.warning_no_network_short), Toast.LENGTH_SHORT).show();
        }
    }
    if (response.hasException) {
        if (LOCAL_LOG)
            Log.v(TAG, "onLoadFinished(): Loader delivered exception; calling handleException()");
        // an error occured

        getSherlockActivity().setSupportProgressBarIndeterminateVisibility(Boolean.FALSE);
        PastyException mException = response.getException();
        handleException(mException);
    } else {
        switch (loader.getId()) {
        case PastyLoader.TASK_CLIPBOARD_FETCH:
            JSONArray Clipboard = response.getClipboard();
            mItems.clear();
            mAdapter.notifyDataSetChanged();
            getListView().invalidateViews();
            try {
                if (Clipboard.length() == 0) {
                    //Clipboard is empty
                    mHelpTextBig.setText(R.string.helptext_PastyActivity_clipboard_empty);
                    mHelpTextSmall.setText(R.string.helptext_PastyActivity_how_to_add);
                } else {
                    for (int i = 0; i < Clipboard.length(); i++) {
                        JSONObject Item = Clipboard.getJSONObject(i);
                        ClipboardItem cbItem = new ClipboardItem(Item.getString("_id"), Item.getString("item"));
                        this.mItems.add(cbItem);
                    }

                    mHelpTextBig.setText(R.string.helptext_PastyActivity_copy);
                    mHelpTextSmall.setText(R.string.helptext_PastyActivity_options);

                    //Assign adapter to ListView
                    ListView listView = (ListView) getSherlockActivity().findViewById(R.id.listItems);
                    listView.setAdapter(mAdapter);
                    listView.setItemsCanFocus(false);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @SuppressLint("NewApi")
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            ClipboardItem Item = mItems.get(position); // get a ClipboardItem from the clicked position
                            if (Item.isLinkified() && prefs.getClickableLinks()) {
                                /* If the clicked item was originally linkified and prefs.getClickableLinks() is true, we manually
                                 * fire an ACTION_VIEW intent to simulate Linkify() behavior
                                 */
                                String url = Item.getText();
                                if (!URLUtil.isValidUrl(url))
                                    url = "http://" + url;
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(url));
                                startActivity(i);
                            } else {
                                /* Else we copy the item to the systems clipboard,
                                 * show a Toast and finish() the activity
                                 */
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    android.content.ClipboardManager sysClipboard = (android.content.ClipboardManager) getSherlockActivity()
                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                    Item.copyToClipboard(sysClipboard);
                                    sysClipboard = null;
                                } else {
                                    ClipboardManager sysClipboard = (ClipboardManager) getSherlockActivity()
                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                    Item.copyToClipboard(sysClipboard);
                                    sysClipboard = null;
                                }
                                Toast.makeText(getSherlockActivity().getApplicationContext(),
                                        getString(R.string.item_copied), Toast.LENGTH_LONG).show();
                                getSherlockActivity().finish();
                            }
                        }
                    });
                    registerForContextMenu(listView);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.hybris.mobile.app.commerce.fragment.CatalogMenuFragment.java

/**
 * Init the catalog list view with a list of categories
 *
 * @param listView/*from ww  w .ja v  a 2 s.  co m*/
 * @param categories
 */
private void initListViewCatalog(ListView listView, List<CategoryHierarchy> categories) {
    if (categories != null) {
        // On click listener for the different categories
        listView.setOnItemClickListener(new CategoryClickListener(categories));

        // Updating the list view
        listView.setAdapter(new CatalogAdapter(getActivity(), categories));
    }
}