Example usage for android.view LayoutInflater from

List of usage examples for android.view LayoutInflater from

Introduction

In this page you can find the example usage for android.view LayoutInflater from.

Prototype

public static LayoutInflater from(Context context) 

Source Link

Document

Obtains the LayoutInflater from the given context.

Usage

From source file:android.support.v7.widget.SearchView.java

public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    final TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs, R.styleable.SearchView,
            defStyleAttr, 0);/*from   w w w . j a  v  a 2 s .  c o m*/
    // Keep the TintManager in case we need it later
    mTintManager = a.getTintManager();

    final LayoutInflater inflater = LayoutInflater.from(context);
    final int layoutResId = a.getResourceId(R.styleable.SearchView_layout, R.layout.abc_search_view);
    inflater.inflate(layoutResId, this, true);

    mSearchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text);
    mSearchSrcTextView.setSearchView(this);

    mSearchEditFrame = findViewById(R.id.search_edit_frame);
    mSearchPlate = findViewById(R.id.search_plate);
    mSubmitArea = findViewById(R.id.submit_area);
    mSearchButton = (ImageView) findViewById(R.id.search_button);
    mGoButton = (ImageView) findViewById(R.id.search_go_btn);
    mCloseButton = (ImageView) findViewById(R.id.search_close_btn);
    mVoiceButton = (ImageView) findViewById(R.id.search_voice_btn);
    mCollapsedIcon = (ImageView) findViewById(R.id.search_mag_icon);

    // Set up icons and backgrounds.
    mSearchPlate.setBackgroundDrawable(a.getDrawable(R.styleable.SearchView_queryBackground));
    mSubmitArea.setBackgroundDrawable(a.getDrawable(R.styleable.SearchView_submitBackground));
    mSearchButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_searchIcon));
    mGoButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_goIcon));
    mCloseButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_closeIcon));
    mVoiceButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_voiceIcon));
    mCollapsedIcon.setImageDrawable(a.getDrawable(R.styleable.SearchView_searchIcon));

    mSearchHintIcon = a.getDrawable(R.styleable.SearchView_searchHintIcon);

    // Extract dropdown layout resource IDs for later use.
    mSuggestionRowLayout = a.getResourceId(R.styleable.SearchView_suggestionRowLayout,
            R.layout.abc_search_dropdown_item_icons_2line);
    mSuggestionCommitIconResId = a.getResourceId(R.styleable.SearchView_commitIcon, 0);

    mSearchButton.setOnClickListener(mOnClickListener);
    mCloseButton.setOnClickListener(mOnClickListener);
    mGoButton.setOnClickListener(mOnClickListener);
    mVoiceButton.setOnClickListener(mOnClickListener);
    mSearchSrcTextView.setOnClickListener(mOnClickListener);

    mSearchSrcTextView.addTextChangedListener(mTextWatcher);
    mSearchSrcTextView.setOnEditorActionListener(mOnEditorActionListener);
    mSearchSrcTextView.setOnItemClickListener(mOnItemClickListener);
    mSearchSrcTextView.setOnItemSelectedListener(mOnItemSelectedListener);
    mSearchSrcTextView.setOnKeyListener(mTextKeyListener);

    // Inform any listener of focus changes
    mSearchSrcTextView.setOnFocusChangeListener(new OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            if (mOnQueryTextFocusChangeListener != null) {
                mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus);
            }
        }
    });
    setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true));

    final int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_android_maxWidth, -1);
    if (maxWidth != -1) {
        setMaxWidth(maxWidth);
    }

    final CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint);
    if (!TextUtils.isEmpty(queryHint)) {
        setQueryHint(queryHint);
    }

    final int imeOptions = a.getInt(R.styleable.SearchView_android_imeOptions, -1);
    if (imeOptions != -1) {
        setImeOptions(imeOptions);
    }

    final int inputType = a.getInt(R.styleable.SearchView_android_inputType, -1);
    if (inputType != -1) {
        setInputType(inputType);
    }

    boolean focusable = true;
    focusable = a.getBoolean(R.styleable.SearchView_android_focusable, focusable);
    setFocusable(focusable);

    a.recycle();

    // Save voice intent for later queries/launching
    mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
    mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

    mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    mDropDownAnchor = findViewById(mSearchSrcTextView.getDropDownAnchor());
    if (mDropDownAnchor != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            addOnLayoutChangeListenerToDropDownAnchorSDK11();
        } else {
            addOnLayoutChangeListenerToDropDownAnchorBase();
        }
    }

    updateViewsVisibility(mIconifiedByDefault);
    updateQueryHint();
}

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

@SuppressWarnings("deprecation")
@Override//from ww w  .  j  a  va 2s  .com
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:net.evecom.android.log.DailyLogListActivity.java

/**
 * ListView""/*from   w  ww.  j ava  2 s .  c  om*/
 */
private void addPageMore() {
    View view = LayoutInflater.from(this).inflate(R.layout.list_page_load, null);
    moreTextView = (TextView) view.findViewById(R.id.more_id);
    loadProgressBar = (LinearLayout) view.findViewById(R.id.load_id);
    listView.addFooterView(view);
    moreTextView.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            // ""
            moreTextView.setVisibility(View.GONE);
            // 
            loadProgressBar.setVisibility(View.VISIBLE);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    // //3
                    // try {
                    // Thread.sleep(3000);
                    // } catch (InterruptedException e) {
                    // e.printStackTrace();
                    // }
                    //  
                    if (null != dailyLogPerson && dailyLogPerson.size() >= pageSize && search == false) {

                        chageListView(dailyLogPerson.size() + 1, pageSize + dailyLogPerson.size());

                    }
                    Message mes = handler.obtainMessage(pageType);
                    handler2.sendMessage(mes);
                }
            }).start();
        }
    });
}

From source file:com.example.android.wearable.quiz.MainActivity.java

/**
 * Sets the question's status to be the default "unanswered." This will be updated when the
 * user chooses an answer for the question on the wearable.
 *///from w  ww.ja va  2 s  . c  om
private void setNewQuestionStatus(String question) {
    quizStatus.setVisibility(View.VISIBLE);
    quizButtons.setVisibility(View.VISIBLE);
    LayoutInflater inflater = LayoutInflater.from(this);
    View questionStatusElem = inflater.inflate(R.layout.question_status_element, null, false);
    ((TextView) questionStatusElem.findViewById(R.id.question)).setText(question);
    ((TextView) questionStatusElem.findViewById(R.id.status)).setText(R.string.question_unanswered);
    questionsContainer.addView(questionStatusElem);
}

From source file:apps.junkuvo.alertapptowalksafely.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());

    ActionBar actionbar = getSupportActionBar();
    if (actionbar != null) {
        actionbar.show();//from  w w w  . jav  a2 s. co  m
    }
    // ????APK???????BG???onCreate??Activity??
    // Intent??????????????
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
        finish();
        return;
    }

    if (!isRunningJunit) {
        setContentView(R.layout.activity_main);

        FirebaseRemoteConfigUtil.initialize();

        LikeView likeView = (LikeView) findViewById(R.id.like_view);
        likeView.setObjectIdAndType(String.format(getString(R.string.app_googlePlay_url), getPackageName()),
                LikeView.ObjectType.PAGE);

        // Create the interstitial.
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.ad_mob_id));

        // Create ad request.
        final AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
                .addTestDevice("1BEC3806A9717F2A87F4D1FC2039D5F2") // An device ID ASUS
                .addTestDevice("64D37FCE47B679A7F4639D180EC4C547").build();

        // Begin loading your interstitial.
        mInterstitialAd.loadAd(adRequest);
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLeftApplication() {
                super.onAdLeftApplication();
                enableNewFunction = true;
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onAdClosed() {
                super.onAdClosed();
                // ?????????????
                if (!enableNewFunction) {
                    // Begin loading your interstitial.
                    mInterstitialAd.loadAd(adRequest);
                } else {
                    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                    final View layout = inflater.inflate(R.layout.new_function_dialog,
                            (ViewGroup) findViewById(R.id.layout_root_new));
                    new MaterialStyledDialog(MainActivity.this).setTitle("?").setDescription(
                            "????????\n???????????")
                            .setCustomView(layout).setIcon(R.drawable.ic_fiber_new_white_48dp)
                            .setHeaderDrawable(R.drawable.pattern_bg_blue)
                            .setPositive(getString(R.string.ok), null).show();

                    RealmUtil.insertHistoryItemAsync(realm, createHistoryItemData(),
                            new RealmUtil.realmTransactionCallbackListener() {
                                @Override
                                public void OnSuccess() {

                                }

                                @Override
                                public void OnError() {

                                }
                            });
                }
            }
        });

        // FIXME : ??????
        AdView mAdView = (AdView) findViewById(R.id.adView);
        //            mAdView.loadAd(adRequest);

        DefaultLayoutPromptView promptView = (DefaultLayoutPromptView) findViewById(R.id.prompt_view);

        final BasePromptViewConfig basePromptViewConfig = new BasePromptViewConfig.Builder()
                .setUserOpinionQuestionTitle(getString(R.string.prompt_title))
                .setUserOpinionQuestionPositiveButtonLabel(getString(R.string.prompt_btn_yes))
                .setUserOpinionQuestionNegativeButtonLabel(getString(R.string.prompt_btn_no))
                .setPositiveFeedbackQuestionTitle(getString(R.string.prompt_title_feedback))
                .setPositiveFeedbackQuestionPositiveButtonLabel(getString(R.string.prompt_btn_sure))
                .setPositiveFeedbackQuestionNegativeButtonLabel(getString(R.string.prompt_btn_notnow))
                .setCriticalFeedbackQuestionTitle(getString(R.string.prompt_title_feedback_2))
                .setCriticalFeedbackQuestionNegativeButtonLabel(getString(R.string.prompt_btn_notnow))
                .setCriticalFeedbackQuestionPositiveButtonLabel(getString(R.string.prompt_btn_sure))
                .setThanksTitle(getString(R.string.prompt_thanks)).build();

        promptView.applyBaseConfig(basePromptViewConfig);
        Amplify.getSharedInstance().promptIfReady(promptView);

        mAnimationBlink = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);

        int buttonColor = ContextCompat.getColor(this, R.color.colorPrimary);
        int buttonPressedColor = ContextCompat.getColor(this, R.color.colorPrimaryDark);
        mbtnStart = (ActionButton) findViewById(R.id.fabStart);
        mbtnStart.setButtonColor(buttonColor);
        mbtnStart.setButtonColorPressed(buttonPressedColor);

        // ?
        new MaterialIntroView.Builder(this).enableDotAnimation(false).enableIcon(true)
                .setFocusGravity(FocusGravity.CENTER).setFocusType(Focus.MINIMUM).setDelayMillis(500)
                .enableFadeAnimation(true).performClick(true).setInfoText(getString(R.string.intro_description))
                .setTarget(mbtnStart).setUsageId(TUTORIAL_ID) //THIS SHOULD BE UNIQUE ID
                .dismissOnTouch(true).show();

        mbtnStart.setOnClickListener(this);

        Intent mAlertServiceIntent = new Intent(MainActivity.this, AlertService.class);

        // ?????????????(???????)
        // ????????
        if (!Utility.isTabletNotPhone(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mTwitter = TwitterUtility.getTwitterInstance(this);
        mCallbackURL = getString(R.string.twitter_callback_url);

        mPlusOneButton = (PlusOneButton) findViewById(R.id.plus_one_button);
        // Refresh the state of the +1 button each time the activity receives focus.
        mPlusOneButton.initialize(
                String.format(getString(R.string.app_googlePlay_url_plusOne), getPackageName()),
                PLUS_ONE_REQUEST_CODE);

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rtlMain);
        relativeLayout.setOnClickListener(this);

        findViewById(R.id.llStepCount).setVisibility(mShouldShowPedometer ? View.VISIBLE : View.INVISIBLE);

        //        // Service?????Activity?Destroy????Activity??????
        //        // UI?Service????????Service??????????Bind????????
        //        // Application????
        //        if (((AlertApplication) getApplication()).IsRunningService()) {
        //            btnIsStarted = false;
        //            setStartButtonFunction(findViewById(R.id.fabStart));
        //        }
        // 
        //            startService(mAlertServiceIntent);
        bindService(mAlertServiceIntent, mConnection, Context.BIND_AUTO_CREATE);

    }

    mIsToastOn = SharedPreferencesUtil.getBoolean(this, SETTING_SHAREDPREF_NAME, "message", true);
    mIsVibrationOn = SharedPreferencesUtil.getBoolean(this, SETTING_SHAREDPREF_NAME, "vibrate", true);
    mToastPosition = SharedPreferencesUtil.getInt(this, SETTING_SHAREDPREF_NAME, "toastPosition",
            Gravity.CENTER);
    mAlertStartAngle = SharedPreferencesUtil.getInt(this, SETTING_SHAREDPREF_NAME, "progress",
            ALERT_ANGLE_INITIAL_VALUE) + ALERT_ANGLE_INITIAL_OFFSET;
    mShouldShowPedometer = SharedPreferencesUtil.getBoolean(this, SETTING_SHAREDPREF_NAME, "pedometer", true);

    // ?????(update??) or ???
    enableNewFunction = RealmUtil.hasHistoryItem(realm) || SharedPreferencesUtil.getBoolean(this,
            AD_STATUS_SHAREDPREF_NAME, "AD_STATUS_SHAREDPREF_NAME", false);

}

From source file:app.cloud9.com.cloud9.NoticeBoard.java

private void initRecyclerView() {
    mRecentRecyclerView = (RecyclerView) findViewById(R.id.recentrecyclerView);
    mRecentRecyclerView.setVisibility(View.GONE);
    mRecentRecyclerView.setHasFixedSize(true);

    mRecentLayoutManager = new LinearLayoutManager(this);

    mRecentRecyclerView.setLayoutManager(mRecentLayoutManager);

    mAdapter = new RecyclerView.Adapter<CustomViewHolder>() {
        @Override/*w  w w .  j av a 2  s  .c  o  m*/
        public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notice_snippet, viewGroup,
                    false);
            return new CustomViewHolder(view);
        }

        @Override
        public void onBindViewHolder(CustomViewHolder viewHolder, int i) {
            viewHolder.noticeSubject.setText(mItems.get(i).getSubject());
            viewHolder.noticeBody.setText(mItems.get(i).getText());
            viewHolder.noticeTime.setText(mItems.get(i).getPosted_at());
            viewHolder.noticePoster.setText(mItems.get(i).getPosted_by());

            // viewHolder.noticeBody.setText(arraylist.get(i).text);
        }

        @Override
        public int getItemCount() {
            return mItems.size();
        }

    };
    mRecentRecyclerView.setAdapter(mAdapter);

    if (mAdapter.getItemCount() == 0) {
        emptyNotice.setVisibility(View.VISIBLE);
        mRecentRecyclerView.setVisibility(View.GONE);

    } else {
        emptyNotice.setVisibility(View.GONE);
        mRecentRecyclerView.setVisibility(View.VISIBLE);

    }

    SwipeDismissRecyclerViewTouchListener touchListener = new SwipeDismissRecyclerViewTouchListener(
            mRecentRecyclerView, new SwipeDismissRecyclerViewTouchListener.DismissCallbacks() {
                @Override
                public boolean canDismiss(int position) {
                    return true;
                }

                @Override
                public void onDismiss(RecyclerView recyclerView, int[] reverseSortedPositions) {
                    for (int position : reverseSortedPositions) {
                        //                                    mLayoutManager.removeView(mLayoutManager.getChildAt(position));
                        mItems.remove(position);
                        mAdapter.notifyItemRemoved(position);
                    }
                    mAdapter.notifyDataSetChanged();
                    Toast.makeText(NoticeBoard.this, "Notice Removed", Toast.LENGTH_SHORT).show();

                    //If no notice available,

                    if (mItems.size() == 0) {
                        //mRecentRecyclerView.setVisibility(View.GONE);
                        emptyNotice.setVisibility(View.VISIBLE);
                    }

                }
            });
    mRecentRecyclerView.setOnTouchListener(touchListener);
    // Setting this scroll listener is required to ensure that during ListView scrolling,
    // we don't look for swipes.
    mRecentRecyclerView.setOnScrollListener(touchListener.makeScrollListener());
    mRecentRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            //Toast.makeText(NoticeBoard.this, "Clicked " + mItems.get(position), Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getBaseContext(), NoticeViewer.class);

            View noticeSubj = view.findViewById(R.id.notice_subject);
            View noticeIcon = view.findViewById(R.id.group_icon);

            View noticeBody = view.findViewById(R.id.notice_body);
            View card = view.findViewById(R.id.card_view);

            Bundle b = new Bundle();
            b.putString("Subject", arraylist.get(position).getSubject());
            b.putString("Text", arraylist.get(position).getText());
            b.putString("Path", arraylist.get(position).getPath());
            b.putString("Posted_by", arraylist.get(position).getPosted_by());
            b.putString("Posted_at", arraylist.get(position).getPosted_at());
            i.putExtras(b);

            String subjectTransitionName = getString(R.string.transition_notice);
            String groupIconTransitionName = getString(R.string.transition_group_icon);
            String bodyTransitionName = getString(R.string.transition_notice_body);
            String cardTransitionName = getString(R.string.transition_card);

            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(NoticeBoard.this,
                    Pair.create(noticeSubj, subjectTransitionName),
                    Pair.create(noticeIcon, groupIconTransitionName),
                    Pair.create(noticeBody, bodyTransitionName), Pair.create(card, cardTransitionName));

            ActivityCompat.startActivity(NoticeBoard.this, i, options.toBundle());
        }
    }));

}

From source file:android.support.v7.view.menu.CascadingMenuPopup.java

/**
 * Prepares and shows the specified menu immediately.
 *
 * @param menu the menu to show// ww w . ja  v a2  s .c  om
 */
private void showMenu(@NonNull MenuBuilder menu) {
    final LayoutInflater inflater = LayoutInflater.from(mContext);
    final MenuAdapter adapter = new MenuAdapter(menu, inflater, mOverflowOnly);

    // Apply "force show icon" setting. There are 3 cases:
    // (1) This is the top level menu and icon spacing is forced. Add spacing.
    // (2) This is a submenu. Add spacing if any of the visible menu items has an icon.
    // (3) This is the top level menu and icon spacing isn't forced. Do not add spacing.
    if (!isShowing() && mForceShowIcon) {
        // Case 1
        adapter.setForceShowIcon(true);
    } else if (isShowing()) {
        // Case 2
        adapter.setForceShowIcon(MenuPopup.shouldPreserveIconSpacing(menu));
    }
    // Case 3: Else, don't allow spacing for icons (default behavior; do nothing).

    final int menuWidth = measureIndividualMenuWidth(adapter, null, mContext, mMenuMaxWidth);
    final MenuPopupWindow popupWindow = createPopupWindow();
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(menuWidth);
    popupWindow.setDropDownGravity(mDropDownGravity);

    final CascadingMenuInfo parentInfo;
    final View parentView;
    if (mShowingMenus.size() > 0) {
        parentInfo = mShowingMenus.get(mShowingMenus.size() - 1);
        parentView = findParentViewForSubmenu(parentInfo, menu);
    } else {
        parentInfo = null;
        parentView = null;
    }

    if (parentView != null) {
        // This menu is a cascading submenu anchored to a parent view.
        popupWindow.setTouchModal(false);
        popupWindow.setEnterTransition(null);

        final @HorizPosition int nextMenuPosition = getNextMenuPosition(menuWidth);
        final boolean showOnRight = nextMenuPosition == HORIZ_POSITION_RIGHT;
        mLastPosition = nextMenuPosition;

        final int[] tempLocation = new int[2];

        // This popup menu will be positioned relative to the top-left edge
        // of the view representing its parent menu.
        parentView.getLocationInWindow(tempLocation);
        final int parentOffsetLeft = parentInfo.window.getHorizontalOffset() + tempLocation[0];
        final int parentOffsetTop = parentInfo.window.getVerticalOffset() + tempLocation[1];

        // By now, mDropDownGravity is the resolved absolute gravity, so
        // this should work in both LTR and RTL.
        final int x;
        if ((mDropDownGravity & Gravity.RIGHT) == Gravity.RIGHT) {
            if (showOnRight) {
                x = parentOffsetLeft + menuWidth;
            } else {
                x = parentOffsetLeft - parentView.getWidth();
            }
        } else {
            if (showOnRight) {
                x = parentOffsetLeft + parentView.getWidth();
            } else {
                x = parentOffsetLeft - menuWidth;
            }
        }

        popupWindow.setHorizontalOffset(x);

        final int y = parentOffsetTop;
        popupWindow.setVerticalOffset(y);
    } else {
        if (mHasXOffset) {
            popupWindow.setHorizontalOffset(mXOffset);
        }
        if (mHasYOffset) {
            popupWindow.setVerticalOffset(mYOffset);
        }
        final Rect epicenterBounds = getEpicenterBounds();
        popupWindow.setEpicenterBounds(epicenterBounds);
    }

    final CascadingMenuInfo menuInfo = new CascadingMenuInfo(popupWindow, menu, mLastPosition);
    mShowingMenus.add(menuInfo);

    popupWindow.show();

    // If this is the root menu, show the title if requested.
    if (parentInfo == null && mShowTitle && menu.getHeaderTitle() != null) {
        final ListView listView = popupWindow.getListView();
        final FrameLayout titleItemView = (FrameLayout) inflater
                .inflate(R.layout.abc_popup_menu_header_item_layout, listView, false);
        final TextView titleView = (TextView) titleItemView.findViewById(android.R.id.title);
        titleItemView.setEnabled(false);
        titleView.setText(menu.getHeaderTitle());
        listView.addHeaderView(titleItemView, null, false);

        // Show again to update the title.
        popupWindow.show();
    }
}

From source file:com.watch.customer.ui.ShopListActivity.java

@SuppressWarnings("deprecation")
private void showAreaPop(int width, int height) {
    layout = (LinearLayout) LayoutInflater.from(ShopListActivity.this).inflate(R.layout.popup_area, null);
    area_grid = (GridView) layout.findViewById(R.id.area_grid);
    area_grid.setOnItemClickListener(this);
    mAreaAdapter = new AreaAdapter();
    area_grid.setAdapter(mAreaAdapter);/*from   ww w .java  2 s  .c  o  m*/
    mPopWin = new PopupWindow(layout, width, LayoutParams.WRAP_CONTENT, true);
    View area_loc = (LinearLayout) layout.findViewById(R.id.area_loc);
    area_loc.setOnClickListener(this);
    mPopWin.setBackgroundDrawable(new BitmapDrawable());
    mPopWin.showAsDropDown(findViewById(R.id.head), 0, 0);
    mPopWin.update();
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

void buildTagViews(NdefMessage[] msgs) {
    if (msgs == null || msgs.length == 0) {
        return;//from ww  w. j a  va  2s .  c o  m
    }
    LayoutInflater inflater = LayoutInflater.from(this);
    // LinearLayout content = mTagContent;
    // Clear out any old views in the content area, for example if
    // you scan
    // two tags in a row.
    // content.removeAllViews();
    // Parse the first message in the list
    // Build views for all of the sub records
    Log.i("TEST", "test");
    List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
    NdefRecord[] ndefRecords = msgs[0].getRecords();
    short tnf = ndefRecords[0].getTnf();

    Log.d("RECORD", "tnf is : " + Short.toString(tnf));

    byte[] type = ndefRecords[0].getType();
    byte[] standard = NdefRecord.RTD_TEXT;

    System.out.println("printing what we got in the message");
    for (byte theByte : type) {
        System.out.println(Integer.toHexString(theByte));
        Log.d("RECORD", Integer.toHexString(theByte));
    }

    System.out.println("printing what the actual val is ");
    for (byte theByte : standard) {
        System.out.println(Integer.toHexString(theByte));
        Log.d("RECORD", Integer.toHexString(theByte));
    }
    if (ndefRecords[0].getType().equals(standard))
        Log.d("RECORD", " type is : RTD_TXT");
    else if (ndefRecords[0].getType().equals(NdefRecord.RTD_URI))
        Log.d("RECORD", " type is : RTD_URI");
    else
        Log.d("RECORD", " type is : none of the 2");
    final int size = records.size();
    for (int i = 0; i < size; i++) {
        ParsedNdefRecord record = records.get(i);
        Log.i("RECORD", record.toString());
        String text;
        if (record instanceof TextRecord) {
            TextRecord t = (TextRecord) record;
            text = t.getText();
        } else {
            UriRecord t = (UriRecord) record;
            text = t.getUri().toString();
        }
        Log.d("WIFI", text);

        /*
         * At this point we have obtained the name of the profile . We
         * should not append .txt and see if the file exists in the
         * /mnt/Profile folder.
         * 
         * If it does exist, then we read the file, and apply various
         * settings
         * 
         * If it does note exists, then we show an error message indicating
         * that the user does not have a profile corresponding to this TAG.
         * Alternatively: We can take him to the create TAG activity where
         * he can create a new TAG with this name.
         */

        String contents[] = text.split("#");
        String filename = null;
        if (contents.length > 1) {

            String readHash = contents[0];
            filename = contents[1];

            Log.d("TAG_VIEWER", "readHash: " + readHash);
            Log.d("TAG_VIEWER", "filename: " + filename);

            if (readHash.equals(Utility.hashOfId)) {
                Log.d("TAG_VIEWER", "Hash Valid");

                File root = Environment.getExternalStorageDirectory();
                String path = root + "/Profiles/" + Utility.userUID + "/";
                String filePath = path + filename + ".txt";
                String settingString = "";
                boolean exists = (new File(path).exists());

                if (exists) {
                    Log.d("TAG_VIEWER", "Found file:" + filePath);
                    /*
                     * Parse the contents of the file, and apply settings
                     */
                    try {

                        FileReader logReader = new FileReader(filePath);
                        BufferedReader in = new BufferedReader(logReader);
                        try {
                            settingString = in.readLine();

                            Log.d("TAG_VIEWER", "In " + filePath + " settingString: " + settingString);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Log.d("TAG_VIEWER", " read(buf) exception");
                            e.printStackTrace();
                        }
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        Log.d("TAG_VIEWER", "FileReader exception");
                        e.printStackTrace();
                    }

                    /*
                     * One call for each setting that we support
                     */
                    StringBuilder returnVal = new StringBuilder();

                    returnVal.append(wifiSetting(settingString));

                    returnVal.append(bluetoothSetting(settingString));

                    returnVal.append(ringerSetting(settingString));

                    launchmusicSetting(settingString);

                    returnVal.append(alarmSetting(settingString));

                    fbSetting(settingString);

                    Log.d("TAG_VIEWER", "the toast should be : " + returnVal.toString());

                    Context context = getApplicationContext();
                    CharSequence toastMessage = returnVal;
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context, toastMessage, duration);
                    toast.show();

                } else {
                    /*
                     * Give the user the option of creating a new tag or
                     * ignoring this tag
                     */
                }

            } else {
                Log.d("TAG_VIEWER", "Hash InValid");
                int duration = Toast.LENGTH_LONG;
                CharSequence msg = "Authentication failure.This tag does not belong to you";
                Toast toast = Toast.makeText(TagViewer.this, msg, duration);
                toast.show();
                finish();
                // return;
            }

        } else {
            // public tag
            Log.d("PUBLIC_TAG", "PUBLIC_TAG");
        }

        // For Vibrate mode
        //

        /** Sending an SMS to a particular number **/

        // Intent intent = new
        // Intent(Intent.ACTION_VIEW,
        // Uri.parse("sms:" + "5189515772"));
        // intent.putExtra("sms_body",
        // "Hi This is a test message");
        // startActivity(intent);

        /** Toggle Airplane mode **/

        // Context context = getApplicationContext();
        // boolean isEnabled =
        // Settings.System.getInt(this.getApplicationContext().getContentResolver(),
        // Settings.System.AIRPLANE_MODE_ON, 0) == 1;
        // Settings.System.putInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON,isEnabled
        // ? 0 : 1);
        // Intent intent = new
        // Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        // intent.putExtra("state", !isEnabled);
        // sendBroadcast(intent);

        /** Launching the browser **/

        // String url = "http://www.google.com";
        // Intent intent = new
        // Intent(Intent.ACTION_VIEW);
        // intent.setData(Uri.parse(url));
        // startActivity(intent);

        /** Check into Facebook **/

        // Bundle params = new Bundle();
        //
        // //String access_token =
        // AndroidDashboardActivity.mPrefs.getString("access_token",
        // null);
        // //params.putString("access_token", access_token);
        // params.putString("place", "203682879660695"); // YOUR PLACE
        // ID
        // params.putString("Message","I m here in this place");
        // JSONObject coordinates = new JSONObject();
        // try
        // {
        // coordinates.put("latitude", 40.756);
        // coordinates.put("longitude", -73.987);
        // }
        // catch (JSONException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        //
        // params.putString("coordinates",coordinates.toString());
        // JSONArray frnd_data=new JSONArray();
        // params.putString("tags", "waves.mpcs@gmail.com");//where xx
        // indicates the User Id
        // String response;
        // try
        // {
        // response = facebook.request("me/checkins", params, "POST");
        // Log.d("Response",response);
        // }
        // catch (FileNotFoundException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // catch (MalformedURLException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // catch (IOException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // //Log.d("Response",response);

        /*
         * TODO: Hashing TODO: Facebook Auth TODO: File Storage (Profile
         * Storage) TODO: Sample Profiles TODO: Social Network Check in
         * TODO: Alarms TODO: Airplane Mode (Enabling NFC while switching to
         * Airplane mode) TODO: NFC Launcher List (Market App) TODO: UI
         */

        // content.addView(record.getView(this, inflater, content, i));
        // inflater.inflate(R.layout.tag_divider, content, true);
    }

}