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, @NonNull List<T> objects) 

Source Link

Document

Constructor

Usage

From source file:nf.frex.android.FrexActivity.java

private void prepareDecorationsDialog(final Dialog dialog) {
    final Registry<DistanceFunction> distanceFunctions = Registries.distanceFunctions;
    int checkedIndex = distanceFunctions.getIndex(view.getDistanceFunctionId());

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            distanceFunctions.getIds());
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final Spinner distanceFunctionSpinner = (Spinner) dialog.findViewById(R.id.distance_function_spinner);
    distanceFunctionSpinner.setAdapter(arrayAdapter);
    distanceFunctionSpinner.setSelection(checkedIndex, false);

    final SeekBarConfigurer dilationSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.dilation_seek_bar), -3.0, 1.0, true, view.getDistanceDilation());
    final SeekBarConfigurer translateXSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.transl_x_seek_bar), -2.5, 2.5, false,
            view.getDistanceTranslateX());
    final SeekBarConfigurer translateYSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.transl_y_seek_bar), -2.5, 2.5, false,
            view.getDistanceTranslateY());

    final CheckBox turbulenceCheckBox = (CheckBox) dialog.findViewById(R.id.turbulence);
    turbulenceCheckBox.setChecked(view.getGeneratorConfig().isTurbulenceEnabled());

    final SeekBarConfigurer turbIntensSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.turb_intens_seek_bar), -1.0, 1.0, true,
            view.getGeneratorConfig().getTurbulenceIntensity());
    final SeekBarConfigurer turbScaleSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.turb_scale_seek_bar), -1.0, 1.0, true,
            view.getGeneratorConfig().getTurbulenceScale());

    Button randomButton = (Button) dialog.findViewById(R.id.random_button);
    randomButton.setOnClickListener(new View.OnClickListener() {
        @Override//from  w  w  w .  j ava  2s .c om
        public void onClick(View v) {
            distanceFunctionSpinner.setSelection((int) (Math.random() * distanceFunctions.getSize()));
            dilationSeekBarConfigurer.setRandomValue();
            translateXSeekBarConfigurer.setRandomValue();
            translateYSeekBarConfigurer.setRandomValue();
            if (Math.random() < 0.5) {
                turbIntensSeekBarConfigurer.setRandomValue();
                turbScaleSeekBarConfigurer.setRandomValue();
            }
        }
    });

    Button okButton = (Button) dialog.findViewById(R.id.ok_button);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int index = distanceFunctionSpinner.getSelectedItemPosition();
            dialog.dismiss();
            view.setDecoratedFractal(true);
            view.setDistanceFunctionId(distanceFunctions.getId(index));
            view.setDistanceDilation(dilationSeekBarConfigurer.getValue());
            view.setDistanceTranslateX(translateXSeekBarConfigurer.getValue());
            view.setDistanceTranslateY(translateYSeekBarConfigurer.getValue());
            view.getGeneratorConfig().setTurbulenceEnabled(turbulenceCheckBox.isChecked());
            view.getGeneratorConfig().setTurbulenceIntensity(turbIntensSeekBarConfigurer.getValue());
            view.getGeneratorConfig().setTurbulenceScale(turbScaleSeekBarConfigurer.getValue());
            view.recomputeAll();
        }
    });
    Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}

From source file:com.krayzk9s.imgurholo.ui.SingleImageFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    final ImgurHoloActivity activity = (ImgurHoloActivity) getActivity();
    final SharedPreferences settings = activity.getApiCall().settings;
    sort = settings.getString("CommentSort", "Best");
    boolean newData = true;
    if (commentData != null) {
        newData = false;//from  w  w  w . j  a  v  a 2  s  .  c o  m
    }

    mainView = inflater.inflate(R.layout.single_image_layout, container, false);
    String[] mMenuList = getResources().getStringArray(R.array.emptyList);
    if (commentAdapter == null)
        commentAdapter = new CommentAdapter(mainView.getContext());
    commentLayout = (ListView) mainView.findViewById(R.id.comment_thread);
    commentLayout.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    if (settings.getString("theme", MainActivity.HOLO_LIGHT).equals(MainActivity.HOLO_LIGHT))
        imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.image_view, null);
    else
        imageLayoutView = (LinearLayout) View.inflate(getActivity(), R.layout.dark_image_view, null);

    mPullToRefreshLayout = (PullToRefreshLayout) mainView.findViewById(R.id.ptr_layout);
    ActionBarPullToRefresh.from(getActivity())
            // Mark All Children as pullable
            .allChildrenArePullable()
            // Set the OnRefreshListener
            .listener(this)
            // Finally commit the setup to our PullToRefreshLayout
            .setup(mPullToRefreshLayout);
    if (savedInstanceState != null && newData) {
        imageData = savedInstanceState.getParcelable("imageData");
        inGallery = savedInstanceState.getBoolean("inGallery");
    }
    LinearLayout layout = (LinearLayout) imageLayoutView.findViewById(R.id.image_buttons);
    TextView imageDetails = (TextView) imageLayoutView.findViewById(R.id.single_image_details);
    layout.setVisibility(View.VISIBLE);
    ImageButton imageFullscreen = (ImageButton) imageLayoutView.findViewById(R.id.fullscreen);
    imageUpvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_good);
    imageDownvote = (ImageButton) imageLayoutView.findViewById(R.id.rating_bad);
    ImageButton imageFavorite = (ImageButton) imageLayoutView.findViewById(R.id.rating_favorite);
    imageComment = (ImageButton) imageLayoutView.findViewById(R.id.comment);
    ImageButton imageUser = (ImageButton) imageLayoutView.findViewById(R.id.user);
    imageScore = (TextView) imageLayoutView.findViewById(R.id.single_image_score);
    TextView imageInfo = (TextView) imageLayoutView.findViewById(R.id.single_image_info);
    Log.d("imageData", imageData.getJSONObject().toString());
    if (imageData.getJSONObject().has("ups")) {
        imageUpvote.setVisibility(View.VISIBLE);
        imageDownvote.setVisibility(View.VISIBLE);
        imageScore.setVisibility(View.VISIBLE);
        imageComment.setVisibility(View.VISIBLE);
        ImageUtils.updateImageFont(imageData, imageScore);
    }
    imageInfo.setVisibility(View.VISIBLE);
    ImageUtils.updateInfoFont(imageData, imageInfo);
    imageUser.setVisibility(View.VISIBLE);
    imageFavorite.setVisibility(View.VISIBLE);
    try {
        if (!imageData.getJSONObject().has("account_url")
                || imageData.getJSONObject().getString("account_url").equals("null")
                || imageData.getJSONObject().getString("account_url").equals("[deleted]"))
            imageUser.setVisibility(View.GONE);
        if (!imageData.getJSONObject().has("vote")) {
            imageUpvote.setVisibility(View.GONE);
            imageDownvote.setVisibility(View.GONE);
        } else {
            if (imageData.getJSONObject().getString("vote") != null
                    && imageData.getJSONObject().getString("vote").equals("up"))
                imageUpvote.setImageResource(R.drawable.green_rating_good);
            else if (imageData.getJSONObject().getString("vote") != null
                    && imageData.getJSONObject().getString("vote").equals("down"))
                imageDownvote.setImageResource(R.drawable.red_rating_bad);
        }
        if (imageData.getJSONObject().getString("favorite") != null
                && imageData.getJSONObject().getBoolean("favorite"))
            imageFavorite.setImageResource(R.drawable.green_rating_favorite);
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
    imageFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.favoriteImage(singleImageFragment, imageData, (ImageButton) view, activity.getApiCall());
        }
    });
    imageUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.gotoUser(singleImageFragment, imageData);
        }
    });
    imageComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Activity activity = getActivity();
            final EditText newBody = new EditText(activity);
            newBody.setHint(R.string.body_hint_body);
            newBody.setLines(3);
            final TextView characterCount = new TextView(activity);
            characterCount.setText("140");
            LinearLayout commentReplyLayout = new LinearLayout(activity);
            newBody.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                    //
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                    characterCount.setText(String.valueOf(140 - charSequence.length()));
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    for (int i = editable.length(); i > 0; i--) {
                        if (editable.subSequence(i - 1, i).toString().equals("\n"))
                            editable.replace(i - 1, i, "");
                    }
                }
            });
            commentReplyLayout.setOrientation(LinearLayout.VERTICAL);
            commentReplyLayout.addView(newBody);
            commentReplyLayout.addView(characterCount);
            new AlertDialog.Builder(activity).setTitle(R.string.dialog_comment_on_image_title)
                    .setView(commentReplyLayout)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            if (newBody.getText() != null && newBody.getText().toString().length() < 141) {
                                HashMap<String, Object> commentMap = new HashMap<String, Object>();
                                try {
                                    commentMap.put("comment", newBody.getText().toString());
                                    commentMap.put("image_id", imageData.getJSONObject().getString("id"));
                                    Fetcher fetcher = new Fetcher(singleImageFragment, "3/comment/",
                                            ApiCall.POST, commentMap,
                                            ((ImgurHoloActivity) getActivity()).getApiCall(), POSTCOMMENT);
                                    fetcher.execute();
                                } catch (JSONException e) {
                                    Log.e("Error!", e.toString());
                                }
                            }
                        }
                    }).setNegativeButton(R.string.dialog_answer_cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // Do nothing.
                        }
                    }).show();
        }
    });
    imageUpvote.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.upVote(singleImageFragment, imageData, imageUpvote, imageDownvote,
                    activity.getApiCall());
            ImageUtils.updateImageFont(imageData, imageScore);
        }
    });
    imageDownvote.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.downVote(singleImageFragment, imageData, imageUpvote, imageDownvote,
                    activity.getApiCall());
            ImageUtils.updateImageFont(imageData, imageScore);
        }
    });
    if (popupWindow != null) {
        popupWindow.dismiss();
    }
    popupWindow = new PopupWindow();
    imageFullscreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageUtils.fullscreen(singleImageFragment, imageData, popupWindow, mainView);
        }
    });
    ArrayAdapter<String> tempAdapter = new ArrayAdapter<String>(mainView.getContext(),
            R.layout.drawer_list_item, mMenuList);
    Log.d("URI", "YO I'M IN YOUR SINGLE FRAGMENT gallery:" + inGallery);
    imageView = (ImageView) imageLayoutView.findViewById(R.id.single_image_view);
    loadImage();
    TextView imageTitle = (TextView) imageLayoutView.findViewById(R.id.single_image_title);
    TextView imageDescription = (TextView) imageLayoutView.findViewById(R.id.single_image_description);

    try {
        String size = String
                .valueOf(NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_WIDTH)))
                + "x"
                + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_HEIGHT))
                + " (" + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_SIZE))
                + "B)";
        String initial = imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE) + " "
                + Html.fromHtml("&#8226;") + " " + size + " " + Html.fromHtml("&#8226;") + " " + "Views: "
                + NumberFormat.getIntegerInstance()
                        .format(imageData.getJSONObject().getInt(ImgurHoloActivity.IMAGE_DATA_VIEWS));
        imageDetails.setText(initial);
        Log.d("imagedata", imageData.getJSONObject().toString());
        if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE).equals("null"))
            imageTitle.setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TITLE));
        else
            imageTitle.setVisibility(View.GONE);
        if (!imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION).equals("null")) {
            imageDescription
                    .setText(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_DESCRIPTION));
            imageDescription.setVisibility(View.VISIBLE);
        } else
            imageDescription.setVisibility(View.GONE);
        commentLayout.addHeaderView(imageLayoutView);
        commentLayout.setAdapter(tempAdapter);
    } catch (JSONException e) {
        Log.e("Text Error!", e.toString());
    }
    if ((savedInstanceState == null || commentData == null) && newData) {
        commentData = new JSONParcelable();
        getComments();
        commentLayout.setAdapter(commentAdapter);
    } else if (newData) {
        commentArray = savedInstanceState.getParcelableArrayList("commentData");
        commentAdapter.addAll(commentArray);
        commentLayout.setAdapter(commentAdapter);
        commentAdapter.notifyDataSetChanged();
    } else if (commentArray != null) {
        commentAdapter.addAll(commentArray);
        commentLayout.setAdapter(commentAdapter);
        commentAdapter.notifyDataSetChanged();
    }
    return mainView;
}

From source file:com.df.app.procedures.CarRecogniseLayout.java

/**
 * ?/*from w  ww.  ja  v a2s.c o  m*/
 * @param array
 * @param mCallback
 * @throws JSONException
 */
private void showModelChooseDialog(String[] array, final OnChooseModelFinished mCallback) throws JSONException {
    array[array.length - 1] = "";

    View view1 = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.popup_layout, null);

    final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view1).create();

    TableLayout contentArea = (TableLayout) view1.findViewById(R.id.contentArea);
    final ListView listView = new ListView(view1.getContext());
    listView.setAdapter(
            new ArrayAdapter<String>(view1.getContext(), android.R.layout.simple_list_item_1, array));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            try {
                mCallback.onFinished(i);
                dialog.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

    contentArea.addView(listView);

    setTextView(view1, R.id.title, getResources().getString(R.string.select_model));

    dialog.show();
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java

@SuppressWarnings("deprecation")
@Override/*from  w  w w .  j  a v a  2s . c o m*/
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring */
    final RelativeLayout widgetView;
    TextView labelTextView;
    TextView valueTextView;
    int widgetLayout;
    String[] splitString;
    OpenHABWidget openHABWidget = getItem(position);
    int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getWidth();
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidgetlist_groupitem;
        break;
    case TYPE_SECTIONSWITCH:
        widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem;
        break;
    case TYPE_SWITCH:
        widgetLayout = R.layout.openhabwidgetlist_switchitem;
        break;
    case TYPE_ROLLERSHUTTER:
        widgetLayout = R.layout.openhabwidgetlist_rollershutteritem;
        break;
    case TYPE_TEXT:
        widgetLayout = R.layout.openhabwidgetlist_textitem;
        break;
    case TYPE_SLIDER:
        widgetLayout = R.layout.openhabwidgetlist_slideritem;
        break;
    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;
    case TYPE_SELECTION:
        widgetLayout = R.layout.openhabwidgetlist_selectionitem;
        break;
    case TYPE_SETPOINT:
        widgetLayout = R.layout.openhabwidgetlist_setpointitem;
        break;
    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_VIDEO_MJPEG:
        widgetLayout = R.layout.openhabwidgetlist_videomjpegitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    case TYPE_COLOR:
        widgetLayout = R.layout.openhabwidgetlist_coloritem;
        break;
    default:
        widgetLayout = R.layout.openhabwidgetlist_genericitem;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }

    // Process the colour attributes
    Integer iconColor = openHABWidget.getIconColor();
    Integer labelColor = openHABWidget.getLabelColor();
    Integer valueColor = openHABWidget.getValueColor();

    // Process widgets icon image
    MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage);
    // Some of widgets, for example Frame doesnt' have an icon, so...
    if (widgetImage != null) {
        if (openHABWidget.getIcon() != null) {
            // This is needed to escape possible spaces and everything according to rfc2396
            String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png");
            //                Log.d(TAG, "Will try to load icon from " + iconUrl);
            // Now set image URL
            widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword);
            if (iconColor != null)
                widgetImage.setColorFilter(iconColor);
            else
                widgetImage.clearColorFilter();
        }
    }
    TextView defaultTextView = new TextView(widgetView.getContext());
    // Get TextView for widget label and set it's color
    labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel);
    // Change label color only for non-frame widgets
    if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) {
        Log.d(TAG, String.format("Setting label color to %d", labelColor));
        labelTextView.setTextColor(labelColor);
    } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME)
        labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    // Get TextView for widget value and set it's color
    valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue);
    if (valueColor != null && valueTextView != null) {
        Log.d(TAG, String.format("Setting value color to %d", valueColor));
        valueTextView.setTextColor(valueColor);
    } else if (valueTextView != null)
        valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    defaultTextView = null;
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        if (labelTextView != null) {
            labelTextView.setText(openHABWidget.getLabel());
            if (valueColor != null)
                labelTextView.setTextColor(valueColor);
        }
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_GROUP:
        if (labelTextView != null && valueTextView != null) {
            splitString = openHABWidget.getLabel().split("\\[|\\]");
            labelTextView.setText(splitString[0]);
            if (splitString.length > 1) { // We have some value
                valueTextView.setText(splitString[1]);
            } else {
                // This is needed to clean up cached TextViews
                valueTextView.setText("");
            }
        }
        break;
    case TYPE_SECTIONSWITCH:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (splitString.length > 1 && valueTextView != null) { // We have some value
            valueTextView.setText(splitString[1]);
        } else {
            // This is needed to clean up cached TextViews
            valueTextView.setText("");
        }
        RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup);
        // As we create buttons in this radio in runtime, we need to remove all
        // exiting buttons first
        sectionSwitchRadioGroup.removeAllViews();
        sectionSwitchRadioGroup.setTag(openHABWidget);
        Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator();
        while (sectionMappingIterator.hasNext()) {
            OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next();
            SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater
                    .from(sectionSwitchRadioGroup.getContext())
                    .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup,
                            false);
            segmentedControlButton.setText(widgetMapping.getLabel());
            segmentedControlButton.setTag(widgetMapping.getCommand());
            if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) {
                if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    segmentedControlButton.setChecked(true);
                } else {
                    segmentedControlButton.setChecked(false);
                }
            } else {
                segmentedControlButton.setChecked(false);
            }
            segmentedControlButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "Button clicked");
                    RadioGroup group = (RadioGroup) view.getParent();
                    if (group.getTag() != null) {
                        OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                        SegmentedControlButton selectedButton = (SegmentedControlButton) view;
                        if (selectedButton.getTag() != null) {
                            sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                        }
                    }
                }
            });
            sectionSwitchRadioGroup.addView(segmentedControlButton);
        }

        sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId);
                if (selectedButton != null) {
                    Log.d(TAG, "Selected " + selectedButton.getText());
                    Log.d(TAG, "Command = " + (String) selectedButton.getTag());
                    //                  radioWidget.getItem().sendCommand((String)selectedButton.getTag());
                    sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                }
            }
        });
        break;
    case TYPE_SWITCH:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch);
        if (openHABWidget.hasItem()) {
            if (openHABWidget.getItem().getStateAsBoolean()) {
                switchSwitch.setChecked(true);
            } else {
                switchSwitch.setChecked(false);
            }
        }
        switchSwitch.setTag(openHABWidget.getItem());
        switchSwitch.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                SwitchCompat switchSwitch = (SwitchCompat) v;
                OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    if (!switchSwitch.isChecked()) {
                        sendItemCommand(linkedItem, "ON");
                    } else {
                        sendItemCommand(linkedItem, "OFF");
                    }
                return false;
            }
        });
        break;
    case TYPE_COLOR:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up);
        ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down);
        ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color);
        colorUpButton.setTag(openHABWidget.getItem());
        colorDownButton.setTag(openHABWidget.getItem());
        colorColorButton.setTag(openHABWidget.getItem());
        colorUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "ON");
                return false;
            }
        });
        colorDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "OFF");
                return false;
            }
        });
        colorColorButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (colorItem != null) {
                    if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                        Log.d(TAG, "Time to launch color picker!");
                        ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(),
                                new OnColorChangedListener() {
                                    public void colorChanged(float[] hsv, View v) {
                                        Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
                                        String newColor = String.valueOf(hsv[0]) + ","
                                                + String.valueOf(hsv[1] * 100) + ","
                                                + String.valueOf(hsv[2] * 100);
                                        OpenHABItem colorItem = (OpenHABItem) v.getTag();
                                        sendItemCommand(colorItem, newColor);
                                    }
                                }, colorItem.getStateAsHSV());
                        colorDialog.setTag(colorItem);
                        colorDialog.show();
                    }
                }
                return false;
            }
        });
        break;
    case TYPE_ROLLERSHUTTER:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up);
        ImageButton rollershutterStopButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_stop);
        ImageButton rollershutterDownButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_down);
        rollershutterUpButton.setTag(openHABWidget.getItem());
        rollershutterStopButton.setTag(openHABWidget.getItem());
        rollershutterDownButton.setTag(openHABWidget.getItem());
        rollershutterUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "UP");
                return false;
            }
        });
        rollershutterStopButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "STOP");
                return false;
            }
        });
        rollershutterDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "DOWN");
                return false;
            }
        });
        break;
    case TYPE_TEXT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            if (splitString.length > 0) {
                labelTextView.setText(splitString[0]);
            } else {
                labelTextView.setText(openHABWidget.getLabel());
            }
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            } else {
                // If value is empty, hide TextView to fix vertical alignment of label
                valueTextView.setVisibility(View.GONE);
                valueTextView.setText("");
            }
        break;
    case TYPE_SLIDER:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar);
        if (openHABWidget.hasItem()) {
            sliderSeekBar.setTag(openHABWidget.getItem());
            sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue());
            sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress());
                    OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag();
                    //                     sliderItem.sendCommand(String.valueOf(seekBar.getProgress()));
                    if (sliderItem != null && seekBar != null)
                        sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress()));
                }
            });
            if (volumeUpWidget == null) {
                volumeUpWidget = sliderSeekBar;
                volumeDownWidget = sliderSeekBar;
            }
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false,
                openHABUsername, openHABPassword);
        //          ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams();
        //          float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight();
        //          imageLayoutParams.height = (int) (screenWidth/imageRatio);
        //          imageImage.setLayoutParams(imageLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        //Always clear the drawable so no images from recycled views appear
        chartImage.setImageDrawable(null);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem != null) {
            if (chartItem.getType().equals("GroupItem")) {
                chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            } else {
                chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            }
            if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) {
                chartUrl += "&service=" + openHABWidget.getService();
            }
        }
        Log.d(TAG, "Chart url = " + chartUrl);
        if (chartImage == null)
            Log.e(TAG, "chartImage == null !!!");
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        chartLayoutParams.height = (int) (screenWidth / 2);
        chartImage.setLayoutParams(chartLayoutParams);
        chartUrl += "&w=" + String.valueOf(screenWidth);
        chartUrl += "&h=" + String.valueOf(screenWidth / 2);
        chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.d(TAG, "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.d(TAG, "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_VIDEO_MJPEG:
        Log.d(TAG, "Video is mjpeg");
        ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage);
        MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername,
                this.openHABPassword, this.getContext());
        mjpegStreamer.setTargetImageView(mjpegImage);
        mjpegStreamer.start();
        if (!mjpegWidgetList.contains(mjpegStreamer))
            mjpegWidgetList.add(mjpegStreamer);
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(
                new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword));
        webWeb.getSettings().setJavaScriptEnabled(true);
        webWeb.loadUrl(openHABWidget.getUrl());
        break;
    case TYPE_SELECTION:
        int spinnerSelectedIndex = -1;
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner);
        selectionSpinner.setOnItemSelectedListener(null);
        ArrayList<String> spinnerArray = new ArrayList<String>();
        Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator();
        while (mappingIterator.hasNext()) {
            OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
            spinnerArray.add(openHABWidgetMapping.getLabel());
            if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null)
                if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    spinnerSelectedIndex = spinnerArray.size() - 1;
                }
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, spinnerArray);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectionSpinner.setAdapter(spinnerAdapter);
        selectionSpinner.setTag(openHABWidget);
        if (spinnerSelectedIndex >= 0) {
            Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex));
            selectionSpinner.setSelection(spinnerSelectedIndex);
        } else {
            Log.d(TAG, "Not setting spinner selected index");
        }
        selectionSpinner.post(new Runnable() {
            @Override
            public void run() {
                selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
                        Log.d(TAG, "Spinner item click on index " + index);
                        Spinner spinner = (Spinner) parent;
                        String selectedLabel = (String) spinner.getAdapter().getItem(index);
                        Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel);
                        OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag();
                        if (openHABWidget != null) {
                            Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel());
                            Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings()
                                    .iterator();
                            while (mappingIterator.hasNext()) {
                                OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
                                if (openHABWidgetMapping.getLabel().equals(selectedLabel)) {
                                    Log.d(TAG, "Spinner onItemSelected found match with "
                                            + openHABWidgetMapping.getCommand());
                                    if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() != null) {
                                        // Only send the command for selection of selected command will change the state
                                        if (!openHABWidget.getItem().getState()
                                                .equals(openHABWidgetMapping.getCommand())) {
                                            Log.d(TAG,
                                                    "Spinner onItemSelected selected label command != current item state");
                                            sendItemCommand(openHABWidget.getItem(),
                                                    openHABWidgetMapping.getCommand());
                                        }
                                    } else if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() == null) {
                                        Log.d(TAG,
                                                "Spinner onItemSelected selected label command and state == null");
                                        sendItemCommand(openHABWidget.getItem(),
                                                openHABWidgetMapping.getCommand());
                                    }
                                }
                            }
                        }
                        //               if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand()))
                        //                  sendItemCommand(openHABWidget.getItem(),
                        //                        openHABWidget.getMapping(index).getCommand());
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
            }
        });
        break;
    case TYPE_SETPOINT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            }
        Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus);
        Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus);
        setPointMinusButton.setTag(openHABWidget);
        setPointPlusButton.setTag(openHABWidget);
        setPointMinusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Minus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue - setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));

            }
        });
        setPointPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Plus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue + setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));
            }
        });
        if (volumeUpWidget == null) {
            volumeUpWidget = setPointPlusButton;
            volumeDownWidget = setPointMinusButton;
        }
        break;
    default:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

From source file:com.mifos.mifosxdroid.online.LoanAccountFragment.java

private void inflateFrequencyPeriodSpinner() {
    showProgress(true);//w w w .j  a  v a2s  .  co  m
    App.apiManager.getLoansAccountTemplate(clientId, productId, new Callback<Response>() {
        @Override

        public void success(final Response result, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            Log.d(LOG_TAG, "");

            final List<TermFrequencyTypeOptions> termFrequencyType = new ArrayList<>();
            // you can use this array to populate your spinner
            final ArrayList<String> termFrequencyTypeNames = new ArrayList<String>();
            //Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                JSONObject obj = new JSONObject(sb.toString());
                if (obj.has("termFrequencyTypeOptions")) {
                    JSONArray termFrequencyTypes = obj.getJSONArray("termFrequencyTypeOptions");
                    for (int i = 0; i < termFrequencyTypes.length(); i++) {
                        JSONObject termFrequencyTypeObject = termFrequencyTypes.getJSONObject(i);
                        TermFrequencyTypeOptions termFrequency = new TermFrequencyTypeOptions();
                        termFrequency.setId(termFrequencyTypeObject.optInt("id"));
                        termFrequency.setValue(termFrequencyTypeObject.optString("value"));
                        termFrequencyType.add(termFrequency);
                        termFrequencyTypeNames.add(termFrequencyTypeObject.optString("value"));
                        termFrequencyTypeIdHashMap.put(termFrequency.getValue(), termFrequency.getId());
                    }

                }
                String stringResult = sb.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "", e);
            }
            final ArrayAdapter<String> termFrequencyTypeAdapter = new ArrayAdapter<>(getActivity(),
                    layout.simple_spinner_item, termFrequencyTypeNames);
            termFrequencyTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
            sp_payment_periods.setAdapter(termFrequencyTypeAdapter);
            sp_payment_periods.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    loanTermFrequency = termFrequencyTypeIdHashMap.get(termFrequencyTypeNames.get(i));
                    Log.d("loanTermFrequency" + termFrequencyTypeNames.get(i),
                            String.valueOf(loanTermFrequency));
                    if (loanTermFrequency != -1) {

                    } else {

                        Toast.makeText(getActivity(), getString(R.string.error_select_frequency),
                                Toast.LENGTH_SHORT).show();

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            showProgress(false);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

            Log.d(LOG_TAG, retrofitError.getLocalizedMessage());

            showProgress(false);
        }
    });
}

From source file:com.nps.micro.view.TestsSectionFragment.java

public void setAvailableDevices(List<String> availableDevices) {
    this.devicesList = availableDevices;
    availableDevicesAdapter = new ArrayAdapter<String>(getActivity(), R.layout.text_view, devicesList);
    availableDevicesListView.setAdapter(availableDevicesAdapter);
    availableDevicesListView.setTextFilterEnabled(true);
    setListViewHeightBasedOnChildren(availableDevicesListView);

    if (selectedDevices.isEmpty()) {
        selectedDevices.addAll(devicesList);
        updateModelSelectedDevices();/*www .  ja v  a  2s  .co  m*/
    }

    selectedDevicesAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, selectedDevices);
    selectedDevicesListView.setListItems(selectedDevices);
    selectedDevicesListView.setAdapter(selectedDevicesAdapter);
    setListViewHeightBasedOnChildren(selectedDevicesListView);
}

From source file:net.phase.wallet.Currency.java

protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
    case DIALOG_URL:
        TextView tv = (TextView) dialog.findViewById(R.id.pasteBinHelpText);
        tv.setMovementMethod(LinkMovementMethod.getInstance());

        break;//from   w w w . j a v  a2s  .c om
    case DIALOG_FILE:
        TextView tvhelp = (TextView) dialog.findViewById(R.id.helpText);
        tvhelp.setMovementMethod(LinkMovementMethod.getInstance());

        Spinner fileSpinner = (Spinner) dialog.findViewById(R.id.fileInput);

        File[] files = Environment.getExternalStorageDirectory().listFiles(fileFilter);

        if (files == null || files.length == 0) {
            toastMessage("No files found on sdcard");
        } else {
            ArrayAdapter<File> adapter = new ArrayAdapter<File>(this, android.R.layout.simple_spinner_item,
                    files);
            fileSpinner.setAdapter(adapter);
        }
        break;
    case DIALOG_PASTE:
        EditText keyText = (EditText) dialog.findViewById(R.id.keysText);

        keyText.setText("");
        break;
    case DIALOG_OPTIONS:
        EditText reqText = (EditText) dialog.findViewById(R.id.reqText);

        reqText.setText(Integer.toString(maxlength));
        Spinner currencySpinner = (Spinner) dialog.findViewById(R.id.currencySpinner);
        Spinner decimalSpinner = (Spinner) dialog.findViewById(R.id.decpointSpinner);

        String current = getActiveCurrency();
        String[] currencies = { current };

        try {
            currencies = Currency.getAvailableCurrencies();
        } catch (IOException e) {
            WalletActivity.toastMessage("Warning: unable to obtain currency information");
        } catch (JSONException e) {
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                currencies);
        currencySpinner.setAdapter(adapter);
        for (int i = 0; i < currencies.length; i++) {
            if (currencies[i].equals(current)) {
                currencySpinner.setSelection(i);
                break;
            }
        }

        Integer[] decimaloptions = { 0, 1, 2, 3, 4, 5 };

        ArrayAdapter<Integer> adapter2 = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item,
                decimaloptions);
        decimalSpinner.setAdapter(adapter2);
        for (int i = 0; i < decimaloptions.length; i++) {
            if (decimaloptions[i].intValue() == decimalpoints) {
                decimalSpinner.setSelection(i);
                break;
            }
        }

        break;
    }
}

From source file:com.cwp.cmoneycharge.activity.AddPayActivity.java

public void VoiceSuccess() { // ??
    if (DialogShowUtil.dialoggettype() != null) {
        type = DialogShowUtil.dialoggettype();
    }/*  ww  w . j a va  2s.c  o m*/
    VoiceDefault = DialogShowUtil.dialogVoiceDefault();
    String textreMark = txtMark.getText().toString();

    if (typemode == "add") { // ?
        if (type == "pay") { // 
            rb1.setChecked(true);
            // corporation_fl.setVisibility(View.GONE);
            // address_fl.setVisibility(View.VISIBLE);
            spdatalist = ptypeDAO.getPtypeName(userid);
            txtMoney.setText(VoiceSave[1]);// ?
            txtMoney.setTextColor(Color.parseColor("#5ea98d"));
            if (VoiceDefault == "notype") { // 
                spType.setSelection(Integer.parseInt(VoiceSave[5]));// 
            } else {
                spType.setSelection(Integer.parseInt(VoiceSave[0]));// 
            }
            txtMark.setText(textreMark + " " + VoiceSave[2]);// 
        } else { // 
            rb2.setChecked(true);
            // corporation_fl.setVisibility(View.VISIBLE);
            // address_fl.setVisibility(View.GONE);
            spdatalist = ptypeDAO.getPtypeName(userid);
            txtMoney.setText(VoiceSave[1]);// ?
            txtMoney.setTextColor(Color.parseColor("#ffff0000"));
            if (VoiceDefault == "notype") { // 
                spType.setSelection(Integer.parseInt(VoiceSave[5]));// 
            } else {
                spType.setSelection(Integer.parseInt(VoiceSave[4]));// 
            }
            txtMark.setText(textreMark + " " + VoiceSave[2]);// 
        }
    } else { // ?
        if (type == "pay") { // 
            rb1.setChecked(true);
            // ?
            spdatalist = ptypeDAO.getPtypeName(userid);
            spdata = spdatalist.toArray(new String[spdatalist.size()]);// tb_itypeid?
            adapter = new ArrayAdapter<String>(AddPayActivity.this, R.layout.spinner, spdata); // ??
            spType.setAdapter(adapter);
            txtMoney.setText(VoiceSave[1]);// ?
            txtMoney.setTextColor(Color.parseColor("#5ea98d"));
            if (VoiceDefault == "notype") { // 
                spType.setSelection(Integer.parseInt(VoiceSave[5]));// 
            } else {
                spType.setSelection(Integer.parseInt(VoiceSave[0]));// 
            }
            txtMark.setText(textreMark + " " + VoiceSave[2]);// 
        } else { // 
            // ?
            rb2.setChecked(true);
            spdatalist = itypeDAO.getItypeName(userid);
            spdata = spdatalist.toArray(new String[spdatalist.size()]);// tb_itypeid?
            adapter = new ArrayAdapter<String>(AddPayActivity.this, R.layout.spinner, spdata); // ??
            spType.setAdapter(adapter);
            txtMoney.setText(VoiceSave[1]);// ?
            txtMoney.setTextColor(Color.parseColor("#ffff0000"));
            if (VoiceDefault == "notype") { // 
                spType.setSelection(Integer.parseInt(VoiceSave[5]));// 
            } else {
                spType.setSelection(Integer.parseInt(VoiceSave[4]));// 
            }
            txtMark.setText(textreMark + " " + VoiceSave[2]);// 
        }
    }
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

private boolean configureEmailAutoComplete(boolean autoShowSuggestions) {
    T.UI();/*from  w  ww. j a  v  a  2s .com*/
    final boolean getAccountsPermissionWasGranted = mService.isPermitted(Manifest.permission.GET_ACCOUNTS);
    if (getAccountsPermissionWasGranted) {
        mAccountManager = new AccountManager(this);
        mAccounts = mAccountManager.getAccounts();
        List<String> emails = new ArrayList<String>();
        for (Account account : mAccounts) {
            if (RegexPatterns.EMAIL.matcher(account.name).matches() && !emails.contains(account.name))
                emails.add(account.name);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, emails);
        mEnterEmailAutoCompleteTextView.setAdapter(adapter);
        mEnterEmailAutoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                requestPin();
            }
        });
        mEnterEmailAutoCompleteTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                mEnterEmailAutoCompleteTextView.setThreshold(1);
                return false;
            }
        });
        if (autoShowSuggestions)
            mEnterEmailAutoCompleteTextView.showDropDown();
    }
    mEnterEmailAutoCompleteTextView.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN)) {
                requestPin();
                return true;
            }
            return false;
        }
    });
    return getAccountsPermissionWasGranted;
}

From source file:com.mifos.mifosxdroid.online.LoanAccountFragment.java

private void inflateLoanFundSpinner() {
    showProgress(true);/*from   w  ww .  j a va  2 s.  c o m*/
    App.apiManager.getLoansAccountTemplate(clientId, productId, new Callback<Response>() {
        @Override

        public void success(final Response result, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            Log.d(LOG_TAG, "");

            final List<LoanFund> loanFund = new ArrayList<>();
            // you can use this array to populate your spinner
            final ArrayList<String> loanFundNames = new ArrayList<String>();
            //Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                JSONObject obj = new JSONObject(sb.toString());
                if (obj.has("fundOptions")) {
                    JSONArray loanFunds = obj.getJSONArray("fundOptions");
                    for (int i = 0; i < loanFunds.length(); i++) {
                        JSONObject loanFundObject = loanFunds.getJSONObject(i);
                        LoanFund fund = new LoanFund();
                        fund.setId(loanFundObject.optInt("id"));
                        fund.setValue(loanFundObject.optString("name"));
                        loanFund.add(fund);
                        loanFundNames.add(loanFundObject.optString("name"));
                        loanFundNameIdHashMap.put(fund.getValue(), fund.getId());
                    }

                }
                String stringResult = sb.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "", e);
            }
            final ArrayAdapter<String> loanFundNameAdapter = new ArrayAdapter<>(getActivity(),
                    layout.simple_spinner_item, loanFundNames);
            loanFundNameAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
            sp_fund.setAdapter(loanFundNameAdapter);
            sp_fund.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    fundId = loanFundNameIdHashMap.get(loanFundNames.get(i));
                    Log.d("fundId " + loanFundNames.get(i), String.valueOf(fundId));
                    if (fundId != -1) {

                    } else {

                        Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT)
                                .show();

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            showProgress(false);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

            Log.d(LOG_TAG, retrofitError.getLocalizedMessage());

            showProgress(false);
        }
    });
}