Example usage for android.widget RadioGroup setOnCheckedChangeListener

List of usage examples for android.widget RadioGroup setOnCheckedChangeListener

Introduction

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

Prototype

public void setOnCheckedChangeListener(OnCheckedChangeListener listener) 

Source Link

Document

Register a callback to be invoked when the checked radio button changes in this group.

Usage

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

@SuppressWarnings("deprecation")
@Override//www. j a v  a2  s .  co 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.blueverdi.rosietheriveter.SitesFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    thisFragment = this;
    setRetainInstance(false);//from www .  j  av a  2  s  .com
    myTour = new MySqliteHelperMyTour(getActivity());
    networkAvailable = Utils.isNetworkAvailable(getActivity());
    buildSitesList();
    view = inflater.inflate(R.layout.sites_fragment, container, false);
    viewContainer = (LinearLayout) view.findViewById(R.id.view_container);
    RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);
    // implementation without nested fragments
    // first initialize the gallery view
    // ---------------------------------
    listLayout = (LinearLayout) inflater.inflate(R.layout.site_gallery_view, viewContainer, false);
    Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    int rotation = display.getRotation();
    switch (rotation) {
    case Surface.ROTATION_0:
    case Surface.ROTATION_180:
        portrait = true;
        arrayLayout = R.layout.site_portrait;
        break;
    case Surface.ROTATION_90:
    case Surface.ROTATION_270:
        portrait = false;
        arrayLayout = R.layout.site_landscape;
        break;
    }

    // now initialize the map view 
    // --------------------------
    mapLayout = (LinearLayout) inflater.inflate(R.layout.site_map_view, viewContainer, false);
    try {
        MapsInitializer.initialize(this.getActivity());
    } catch (Exception e) {
        e.printStackTrace();

    }
    mapView = (MapView) mapLayout.findViewById(R.id.siteMap);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
            map.getUiSettings().setMyLocationButtonEnabled(false);
            if (!networkAvailable) {
                Toast.makeText(thisFragment.getActivity(),
                        thisFragment.getActivity().getString(R.string.internet_required), Toast.LENGTH_LONG)
                        .show();
            }

            //      map.setMyLocationEnabled(true);
            //                 CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(SITES, 0);
            //                 map.animateCamera(cameraUpdate);

            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(SITES, 0);
            if (networkAvailable) {
                map.animateCamera(cameraUpdate);
            } else {
                map.moveCamera(cameraUpdate);

            }
            markers = new HashMap<String, Site>();
            for (Site s : sites) {
                LatLng ll = new LatLng(Double.parseDouble(s.getString(Site.LATITUDE)),
                        Double.parseDouble(s.getString(Site.LONGITUDE)));
                Marker marker = map.addMarker(new MarkerOptions().position(ll).title(s.getString(Site.NAME)));
                markers.put(marker.getId(), s);
            }
            map.setOnMarkerClickListener(new OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    Site s = markers.get(marker.getId());
                    Intent i = new Intent(getActivity(), SiteActivity.class);
                    i.putExtra(Site.PARCEL_NAME, s);
                    SiteDetails sd = s.getDetails();
                    if (sd != null) {
                        i.putExtra(SiteDetails.PARCEL_NAME, sd);
                    }
                    startActivity(i);
                    getActivity().overridePendingTransition(R.anim.zoom_in, 0);
                    return true;
                }
            });
        }
    });
    try {
        container.removeAllViews();
    } catch (Exception e) {
        MyLog.d(TAG, "container evaporated inside onCreateView");
        return view;
    }
    if (startInMapView) {
        RadioButton rb = (RadioButton) view.findViewById(R.id.radioMapView);
        rb.setChecked(true);
        setMap();
    } else {
        setGallery();
    }
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.radioListView) {
                setGallery();
            } else {
                Toast.makeText(getActivity(), getString(R.string.getting_map), Toast.LENGTH_LONG).show();
                setMap();
            }
        }
    });
    return view;
}

From source file:com.blueverdi.rosietheriveter.MoreFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setRetainInstance(false);// www .j  a v  a  2s . c  om
    thisFragment = this;
    myTour = new MySqliteHelperMyTour(getActivity());
    networkAvailable = Utils.isNetworkAvailable(getActivity());
    buildSitesList();
    view = inflater.inflate(R.layout.more_fragment, container, false);
    viewContainer = (LinearLayout) view.findViewById(R.id.view_container);
    RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);
    // implementation without nested fragments
    // first initialize the gallery view
    // ---------------------------------
    listLayout = (LinearLayout) inflater.inflate(R.layout.site_gallery_view, viewContainer, false);
    Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    int rotation = display.getRotation();
    switch (rotation) {
    case Surface.ROTATION_0:
    case Surface.ROTATION_180:
        portrait = true;
        arrayLayout = R.layout.site_portrait;
        break;
    case Surface.ROTATION_90:
    case Surface.ROTATION_270:
        portrait = false;
        arrayLayout = R.layout.site_landscape;
        break;
    }
    ListView listview = (ListView) listLayout.findViewById(R.id.siteListView);

    // now initialize the map view 
    // --------------------------
    mapLayout = (LinearLayout) inflater.inflate(R.layout.site_map_view, viewContainer, false);
    try {
        MapsInitializer.initialize(this.getActivity());
    } catch (Exception e) {
        e.printStackTrace();

    }
    mapView = (MapView) mapLayout.findViewById(R.id.siteMap);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
            map.getUiSettings().setMyLocationButtonEnabled(false);
            if (!networkAvailable) {
                thisFragment.getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), getString(R.string.internet_required), Toast.LENGTH_LONG)
                                .show();

                    }
                });
            }

            map.setOnCameraChangeListener(new OnCameraChangeListener() {

                @Override
                public void onCameraChange(CameraPosition arg0) {
                    map.setOnCameraChangeListener(null);
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(SITES, 0);
                    if (networkAvailable) {
                        map.animateCamera(cameraUpdate);
                    } else {
                        map.moveCamera(cameraUpdate);
                    }
                }
            });
            markers = new HashMap<String, Site>();
            for (Site s : sites) {
                LatLng ll = new LatLng(Double.parseDouble(s.getString(Site.LATITUDE)),
                        Double.parseDouble(s.getString(Site.LONGITUDE)));
                Marker marker = map.addMarker(new MarkerOptions().position(ll).title(s.getString(Site.NAME)));
                markers.put(marker.getId(), s);
            }
            map.setOnMarkerClickListener(new OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    Site s = markers.get(marker.getId());
                    Intent i = new Intent(getActivity(), SiteActivity.class);
                    i.putExtra(Site.PARCEL_NAME, s);
                    startActivity(i);
                    getActivity().overridePendingTransition(R.anim.zoom_in, 0);
                    return true;
                }
            });
        }
    });
    try {
        container.removeAllViews();
    } catch (Exception e) {
        MyLog.d(TAG, "container evaporated inside onCreateView");
        return view;
    }
    if (startInMapView) {
        RadioButton rb = (RadioButton) view.findViewById(R.id.radioMapView);
        rb.setChecked(true);
        setMap();
    } else {
        setGallery();
    }
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.radioListView) {
                setGallery();
            } else {
                Toast.makeText(getActivity(), getString(R.string.getting_map), Toast.LENGTH_LONG).show();
                setMap();
            }
        }
    });
    return view;
}

From source file:com.willowtreeapps.spurceexampleapp.fragments.ControlsFragment.java

@Nullable
@Override//from  w  ww  . j a v a2 s .c o m
public View onCreateView(LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.controls_fragment, container, false);

    parent = (GridLayout) ((SpruceActivity) getActivity()).parent;
    children = ((SpruceActivity) getActivity()).children;
    sortDropDown = ((SpruceActivity) getActivity()).sortDropDown;

    linearRadioGroup = (RadioGroup) rootView.findViewById(R.id.directional_radio_group);
    corneredRadioGroup = (RadioGroup) rootView.findViewById(R.id.cornered_radio_group);
    positionalRadioGroup = (RadioGroupGridLayout) rootView.findViewById(R.id.positional_radio_group);
    RadioGroup verticalWeightedRadioGroup = (RadioGroup) rootView
            .findViewById(R.id.vertical_weighted_radio_group);
    RadioGroup horizontalWeightedRadioGroup = (RadioGroup) rootView
            .findViewById(R.id.horizontal_weighted_radio_group);
    verticalWeightLayout = (LinearLayout) rootView.findViewById(R.id.vertical_weight);
    horizontalWeightLayout = (LinearLayout) rootView.findViewById(R.id.horizontal_weight);
    linearReversed = (CheckBox) rootView.findViewById(R.id.linear_reversed);
    seekBar = (SeekBar) rootView.findViewById(R.id.animation_seek);
    animationEndText = (TextView) rootView.findViewById(R.id.animation_end);
    seekBarTitle = (TextView) rootView.findViewById(R.id.seek_bar_title);
    codeSample = (EditText) rootView.findViewById(R.id.code_sample);

    animators = new Animator[] { DefaultAnimations.shrinkAnimator(parent, /*duration=*/800),
            DefaultAnimations.fadeInAnimator(parent, /*duration=*/800) };

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resetChildViewsAndStartSort();
        }
    };
    container.setOnClickListener(click);
    parent.setOnClickListener(click);

    sortDropDown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case CORNERED_SORT:
            case INLINE_SORT:
                linearRadioGroup.setVisibility(View.GONE);
                linearReversed.setVisibility(View.VISIBLE);
                positionalRadioGroup.setVisibility(View.GONE);
                verticalWeightLayout.setVisibility(View.GONE);
                horizontalWeightLayout.setVisibility(View.GONE);
                corneredRadioGroup.setVisibility(View.VISIBLE);
                break;
            case LINEAR_SORT:
                linearRadioGroup.setVisibility(View.VISIBLE);
                linearReversed.setVisibility(View.VISIBLE);
                positionalRadioGroup.setVisibility(View.GONE);
                verticalWeightLayout.setVisibility(View.GONE);
                horizontalWeightLayout.setVisibility(View.GONE);
                corneredRadioGroup.setVisibility(View.GONE);
                break;
            case CONTINUOUS_SORT:
            case RADIAL_SORT:
                positionalRadioGroup.setVisibility(View.VISIBLE);
                verticalWeightLayout.setVisibility(View.GONE);
                horizontalWeightLayout.setVisibility(View.GONE);
                linearReversed.setVisibility(View.VISIBLE);
                linearRadioGroup.setVisibility(View.GONE);
                corneredRadioGroup.setVisibility(View.GONE);
                break;
            case CONTINUOUS_WEIGHTED_SORT:
                positionalRadioGroup.setVisibility(View.VISIBLE);
                verticalWeightLayout.setVisibility(View.VISIBLE);
                horizontalWeightLayout.setVisibility(View.VISIBLE);
                linearReversed.setVisibility(View.VISIBLE);
                linearRadioGroup.setVisibility(View.GONE);
                corneredRadioGroup.setVisibility(View.GONE);
                break;
            default:
                linearReversed.setVisibility(View.GONE);
                positionalRadioGroup.setVisibility(View.GONE);
                verticalWeightLayout.setVisibility(View.GONE);
                horizontalWeightLayout.setVisibility(View.GONE);
                linearRadioGroup.setVisibility(View.GONE);
                corneredRadioGroup.setVisibility(View.GONE);
                break;
            }
            resetChildViewsAndStartSort();
        }

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

        }
    });

    // set default vertical weight
    verticalWeight = ContinuousWeightedSort.MEDIUM_WEIGHT;
    verticalWeightedRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
            case R.id.vertical_light:
                verticalWeight = ContinuousWeightedSort.LIGHT_WEIGHT;
                break;
            case R.id.vertical_medium:
                verticalWeight = ContinuousWeightedSort.MEDIUM_WEIGHT;
                break;
            case R.id.vertical_heavy:
                verticalWeight = ContinuousWeightedSort.HEAVY_WEIGHT;
                break;
            }
            resetChildViewsAndStartSort();
        }
    });

    // set default horizontal weight
    horizontalWeight = ContinuousWeightedSort.MEDIUM_WEIGHT;
    horizontalWeightedRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
            case R.id.horizontal_light:
                horizontalWeight = ContinuousWeightedSort.LIGHT_WEIGHT;
                break;
            case R.id.horizontal_medium:
                horizontalWeight = ContinuousWeightedSort.MEDIUM_WEIGHT;
                break;
            case R.id.horizontal_heavy:
                horizontalWeight = ContinuousWeightedSort.HEAVY_WEIGHT;
                break;
            }
            resetChildViewsAndStartSort();
        }
    });

    // set default direction
    direction = LinearSort.Direction.BOTTOM_TO_TOP;
    linearRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
            case R.id.bottom_to_top:
                direction = LinearSort.Direction.BOTTOM_TO_TOP;
                break;
            case R.id.top_to_bottom:
                direction = LinearSort.Direction.TOP_TO_BOTTOM;
                break;
            case R.id.left_to_right:
                direction = LinearSort.Direction.LEFT_TO_RIGHT;
                break;
            case R.id.right_to_left:
                direction = LinearSort.Direction.RIGHT_TO_LEFT;
                break;
            }
            resetChildViewsAndStartSort();
        }
    });

    // set default corner
    corner = CorneredSort.Corner.TOP_LEFT;
    corneredRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
            case R.id.top_left:
                corner = CorneredSort.Corner.TOP_LEFT;
                break;
            case R.id.top_right:
                corner = CorneredSort.Corner.TOP_RIGHT;
                break;
            case R.id.bottom_left:
                corner = CorneredSort.Corner.BOTTOM_LEFT;
                break;
            case R.id.bottom_right:
                corner = CorneredSort.Corner.BOTTOM_RIGHT;
                break;
            }
            resetChildViewsAndStartSort();
        }
    });

    linearReversed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            resetChildViewsAndStartSort();
        }
    });

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            resetChildViewsAndStartSort();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    positionalRadioGroup.setGroupChildChangedListener(this);
    resetChildViewsAndStartSort();

    return rootView;
}

From source file:org.thoughtland.xlocation.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;/*  w w  w  .j  a v  a  2s.c  o  m*/

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        setTitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        setTitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        setTitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        setTitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        setTitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spAdapter.add(getString(R.string.title_default));
    for (int i = 1; i <= 4; i++)
        spAdapter.add(getString(R.string.title_alternate) + " " + i);
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setText(R.string.menu_toggle);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}

From source file:biz.bokhorst.xprivacy.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;/*  w  w w . j  av  a 2  s.co  m*/

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);
    setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar));

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        getSupportActionBar().setSubtitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        getSupportActionBar().setSubtitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        getSupportActionBar().setSubtitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        getSupportActionBar().setSubtitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        getSupportActionBar().setSubtitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    String defaultName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, "0",
            getString(R.string.title_default));
    spAdapter.add(defaultName);
    for (int i = 1; i <= 4; i++) {
        String alternateName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, Integer.toString(i),
                getString(R.string.title_alternate) + " " + i);
        spAdapter.add(alternateName);
    }
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setVisibility(View.GONE);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}