Example usage for android.widget ArrayAdapter ArrayAdapter

List of usage examples for android.widget ArrayAdapter ArrayAdapter

Introduction

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

Prototype

public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @IdRes int textViewResourceId,
        @NonNull List<T> objects) 

Source Link

Document

Constructor

Usage

From source file:it.crs4.most.ehrlib.widgets.DvCodedTextAsListWidget.java

/**
 * Setup list view adapter./*from   ww w.  ja v  a  2 s .  co  m*/
 */
private void setupListViewAdapter() {
    Log.d(TAG, "Creazione adapter");
    this.adapter = new ArrayAdapter<String>(_context, R.layout.dv_coded_text_listview_row, R.id.txt_row,
            getOptions());

    list.setAdapter(adapter);

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "CLICKING ON:" + position);
            currentSelectionIndex = position;
            list.setItemChecked(getDatatype().getSelectedOptionIndex(), false);
            list.setItemChecked(currentSelectionIndex, true);
        }
    });

    list.setSelection(0);
}

From source file:com.example.research.whatis.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    Log.e("CLicked Menu", String.valueOf(id));
    Log.e("CLicked action", String.valueOf(R.id.action_settings));
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        TextView view = (TextView) findViewById(R.id.textView);
        view.setVisibility(View.GONE);
        ListView lView = (ListView) findViewById(R.id.listView);
        lView.setVisibility(View.VISIBLE);

        ArrayList<String> storedWords = dbHelper.getAllWords();
        Log.e("SQLite", storedWords.toString());
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.activity_listview, R.id.wordsLabel,
                storedWords);//  w  w  w. j  a  va 2s  .c  o  m

        lView.setAdapter(arrayAdapter);
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.mohammedsazidalrashid.android.sunshine.ForecastFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);

    mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.light_blue_500, R.color.orange_500, R.color.teal500,
            R.color.green_500);//from w  ww .  j  av a2  s . co  m

    mForecastAdapater = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast,
            R.id.list_item_forecast_textview, new ArrayList<String>());

    final ListView listviewForecast = (ListView) rootView.findViewById(R.id.listview_forecast);
    listviewForecast.setAdapter(mForecastAdapater);

    listviewForecast.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String forecast = mForecastAdapater.getItem(position);
            MainActivity.bundleForFragments.putString(EXTRA_FORECAST, forecast);
            getActivity().getFragmentManager().beginTransaction().addToBackStack(null)
                    .setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim,
                            R.animator.enter_anim_reverse, R.animator.exit_anim_reverse)
                    .replace(R.id.container, new DetailsFragment()).commit();
        }
    });

    listviewForecast.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int topRowVerticalPosition = (listviewForecast == null || listviewForecast.getChildCount() == 0) ? 0
                    : listviewForecast.getChildAt(0).getTop();
            mSwipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
        }
    });

    return rootView;
}

From source file:gov.sfmta.sfpark.MainScreenActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    MYLOG("onCreate");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);// w  ww.jav  a  2s.  c  om

    // Set up ActionBar
    ActionBar ab = getSupportActionBar();
    ab.setDisplayShowTitleEnabled(false);
    ab.setIcon(R.drawable.logo_header);
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ab.addTab(ab.newTab().setText("Price").setTabListener(new TabListener()));
    ab.addTab(ab.newTab().setText("Availability").setTabListener(new TabListener()));

    // Dropdown navigation
    final String[] dropdownValues = getResources().getStringArray(R.array.dropdown);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(ab.getThemedContext(),
            R.layout.sherlock_spinner_item, android.R.id.text1, dropdownValues);
    adapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
    ab.setListNavigationCallbacks(adapter, this);

    if (SFparkActivity.DEBUG) {
        debugText = (TextView) findViewById(R.id.debugText);
        debugText.setText("Debug String");
        debugText.setVisibility(View.VISIBLE);
    }

    legendlabel = (TextView) findViewById(R.id.legendText);
    legendImage = (ImageView) findViewById(R.id.keyImage);

    // DoubleTapMapView... is a mapview that you can double-tap. :-/
    mapView = new DoubleTapMapView(this);
    FrameLayout fl = (FrameLayout) findViewById(R.id.mapframe);
    fl.addView(mapView, 0, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

    mapView.setBuiltInZoomControls(true);
    mc = mapView.getController();

    // Creating and initializing Map
    GeoPoint p = getPoint(INITIAL_LATITUDE, INITIAL_LONGITUDE);

    mc.setCenter(p);
    mc.setZoom(14);

    startLocation();

    showPrice = true;

    enablePanToMe();
    reset();
}

From source file:it.unipr.ce.dsg.gamidroid.activities.BuildingLookupActivity.java

/**
 * Method to process the JSon descriptor of the resource the node looked for, when it is received.
 *//* w  w  w .  j  a va 2 s. c  om*/
private void processSearchedResource(String jsonDescriptor) {
    try {
        JSONObject obj = new JSONObject(jsonDescriptor);
        String name = obj.getString("name");
        JSONObject subjectObj = obj.getJSONObject("subject");

        if (name.equalsIgnoreCase(buildingMessageType)) {
            String subjectValue = subjectObj.getString("value");
            Gson gson = new Gson();
            floors = gson.fromJson(subjectValue, new TypeToken<List<FloorStruct>>() {
            }.getType());

            runOnUiThread(new Runnable() {
                public void run() {
                    List<String> listString = new ArrayList<String>();
                    for (int i = 0; i < floors.size(); i++) {
                        listString.add(context.getString(R.string.floor) + " " + floors.get(i).getName());
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.list_item_floor,
                            R.id.textItem, listString);
                    setListAdapter(adapter);
                }
            });
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:android.preference.MultiSelectDragListPreference.java

@Override
protected void onPrepareDialogBuilder(Builder builder) {
    super.onPrepareDialogBuilder(builder);

    if (mEntries == null || mEntryValues == null) {
        throw new IllegalStateException(
                "MultiSelectListPreference requires an entries array and " + "an entryValues array.");
    }//from www. j av a 2  s .  co  m

    String[] entries = new String[mEntries.length];
    for (int i = 0; i < mEntries.length; i++) {
        entries[i] = mEntries[i].toString();
    }

    boolean[] selectedItems = getSelectedItems();

    ArrayList<String> orderedList = new ArrayList<String>();
    int n = selectedItems.length;

    for (String value : mValues) {
        int index = ArrayUtils.indexOf(mEntryValues, value);
        orderedList.add(mEntries[index].toString());
    }

    for (int i = 0; i < mEntries.length; i++) {
        if (!mValues.contains(mEntryValues[i]))
            orderedList.add(mEntries[i].toString());
    }

    adapter = new ArrayAdapter<String>(getContext(), R.layout.item_list_preference_multi_drag, R.id.text,
            orderedList);
    listView = new DragSortListView(getContext(), null);
    listView.setAdapter(adapter);

    listView.setDropListener(onDrop);
    listView.setDragEnabled(true);
    listView.setFloatAlpha(0.8f);

    DragSortController controller = new DragSortController(listView);
    controller.setDragHandleId(R.id.drag_handle);
    controller.setRemoveEnabled(false);
    controller.setSortEnabled(true);
    controller.setBackgroundColor(0xFFFFFF);
    controller.setDragInitMode(DragSortController.ON_DOWN);

    listView.setFloatViewManager(controller);
    listView.setOnTouchListener(controller);

    builder.setView(listView);
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            mPreferenceChanged = true;
            refreshNewValues();
        }
    });

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    for (int i = 0; i < n; i++) {
        listView.setItemChecked(i, i < mValues.size());
    }

    /*
     * boolean [] checkedItems = getSelectedItems();
     * builder.setMultiChoiceItems(mEntries, checkedItems,
     * new DialogInterface.OnMultiChoiceClickListener() {
     * public void onClick(DialogInterface dialog, int which, boolean 
     * isChecked) {
     * if (isChecked) {
     * mPreferenceChanged |= mNewValues.add(mEntryValues[which].toString());
     * } else {
     * mPreferenceChanged |=
     * mNewValues.remove(mEntryValues[which].toString());
     * }
     * }
     * });
     */
    mNewValues.clear();
    mNewValues.addAll(mValues);
}

From source file:com.example.office365sample.MainActivity.java

private void updateList(final List<IMessage> messages) {
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                ArrayAdapter<IMessage> adapter = new ArrayAdapter<IMessage>(MainActivity.this,
                        android.R.layout.simple_list_item_activated_2, android.R.id.text1, messages) {
                    @Override/*from   w w w . j ava2  s  .c  o m*/
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);
                        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                        TextView text2 = (TextView) view.findViewById(android.R.id.text2);

                        // get list of recipients and just display first one
                        Collection<Recipient> recipients = messages.get(position).getToRecipients();
                        if (recipients != null && recipients.size() > 0) {
                            Recipient first = ((Recipient) recipients.toArray()[0]);
                            String recipientEmail = first.getAddress();
                            text1.setText("To: " + recipientEmail);
                        } else {
                            text1.setText("<no recipients>");
                        }

                        // show subject
                        text2.setText("Subject: " + messages.get(position).getSubject());
                        return view;
                    }
                };

                listViewMessages.setAdapter(adapter);
                if (!adapter.isEmpty()) {
                    btnSendMessage.setEnabled(true);
                } else {
                    btnSendMessage.setEnabled(false);
                }
            } catch (Exception e) {
                Log.e(TAG, "error", e);
            }
        }
    });
}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * First configure the Universal Image Downloader,
 * then we set the main layout to be activity_main.xml
 * and we add the slide menu items./*from   www.  j av a2 s.c  o  m*/
 *
 * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false);
    ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton);
    drawerBackButton.setOnClickListener(onDrawerBackButton);
    mDrawerList.addHeaderView(header);
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.bringToFront();
    }

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            toolbar, R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // calling onPrepareOptionsMenu() to show search view
            invalidateOptionsMenu();
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // calling onPrepareOptionsMenu() to hide search view
            invalidateOptionsMenu();
            syncState();
        }

        // updates the title, toolbar transparency and search view
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (slideOffset > .55 && !isDrawerOpen) {
                // opening drawer
                // mDrawerTitle is app title
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
                isDrawerOpen = true;
            } else if (slideOffset < .45 && isDrawerOpen) {
                // closing drawer
                // mTitle is title of the current view, can be movies, tv shows or movie title
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
                isDrawerOpen = false;
            }
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the action bar title to set padding
    TextView titleTextView = null;

    try {
        Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(toolbar);
    } catch (NoSuchFieldException e) {

    } catch (IllegalAccessException e) {

    }
    if (titleTextView != null) {
        float scale = getResources().getDisplayMetrics().density;
        titleTextView.setPadding((int) scale * 15, 0, 0, 0);
    }

    phone = getResources().getBoolean(R.bool.portrait_only);

    searchDB = new SearchDB(getApplicationContext());

    if (savedInstanceState == null) {
        // Check orientation and lock to portrait if we are on phone
        if (phone) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        // on first time display view for first nav item
        displayView(1);

        // Use hockey module to check for updates
        checkForUpdates();

        // Universal Loader options and configuration.
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
                .showImageOnLoading(R.drawable.placeholder_default)
                .showImageForEmptyUri(R.drawable.placeholder_default)
                .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build();
        Context context = this;
        File cacheDir = StorageUtils.getCacheDirectory(context);
        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);

        // Check cache size
        long size = 0;
        File[] filesCache = cacheDir.listFiles();
        for (File file : filesCache) {
            size += file.length();
        }
        if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) {
            ImageLoader.getInstance().getDiskCache().clear();
            searchDB.cleanSuggestionRecords();
        }

    } else {
        oldPos = savedInstanceState.getInt("oldPos");
        currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos");
        currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos");
        restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState");
        restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState");
        movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle");
        castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle");
        tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle");
        currOrientation = savedInstanceState.getInt("currOrientation");
        lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie");
        lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV");
        lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits");
        saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment");

        FragmentManager fm = getFragmentManager();
        // prevent the following bug: go to gallery preview -> swap orientation ->
        // go to movies list -> swap orientation -> action bar bugged
        // so if we are not on gallery preview we show toolbar
        if (fm.getBackStackEntryCount() == 0
                || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (getSupportActionBar() != null && !getSupportActionBar().isShowing())
                        getSupportActionBar().show();
                }
            });
        }
    }

    // Get reference for the imageLoader
    imageLoader = ImageLoader.getInstance();

    // Options used for the backdrop image in movie and tv details and gallery
    optionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black)
            .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build();
    optionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black)
            .showImageOnFail(R.color.black).cacheOnDisk(true).build();

    // Options used for the backdrop image in movie and tv details and gallery
    backdropOptionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();
    backdropOptionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();

    trailerListView = new TrailerList();
    galleryListView = new GalleryList();

    if (currOrientation != getResources().getConfiguration().orientation)
        orientationChanged = true;

    currOrientation = getResources().getConfiguration().orientation;

    iconConstantSpecialCase = 0;
    if (phone) {
        iconMarginConstant = 0;
        iconMarginLandscape = 0;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        if (width <= 480 && height <= 800)
            iconConstantSpecialCase = -70;

        // used in MovieDetails, CastDetails, TVDetails onMoreIconClick
        // to check whether the animation should be in up or down direction
        threeIcons = 128;
        threeIconsToolbar = 72;
        twoIcons = 183;
        twoIconsToolbar = 127;
        oneIcon = 238;
        oneIconToolbar = 182;
    } else {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            iconMarginConstant = 232;
            iconMarginLandscape = 300;

            threeIcons = 361;
            threeIconsToolbar = 295;
            twoIcons = 416;
            twoIconsToolbar = 351;
            oneIcon = 469;
            oneIconToolbar = 407;
        } else {
            iconMarginConstant = 82;
            iconMarginLandscape = 0;

            threeIcons = 209;
            threeIconsToolbar = 146;
            twoIcons = 264;
            twoIconsToolbar = 200;
            oneIcon = 319;
            oneIconToolbar = 256;
        }

    }

    dateFormat = android.text.format.DateFormat.getDateFormat(this);
}

From source file:com.groundupworks.wings.gcp.GoogleCloudPrintSettingsActivity.java

private void onPrinterSearchResult(final JacksonPrinterSearchResult result) {
    final List<Printer> printers = result.getPrinters();
    if (printers != null && printers.size() > 0) {
        mPrinterSpinner.setAdapter(new ArrayAdapter<Printer>(GoogleCloudPrintSettingsActivity.this,
                R.layout.gcp_settings_spinner_item, R.id.activity_main_spinner_item_text, printers));
    } else {//from  w  ww .  jav a2s.  c o  m
        Toast.makeText(getApplicationContext(), R.string.wings_gcp__settings__error_no_printer,
                Toast.LENGTH_SHORT).show();
    }
}