Example usage for android.widget LinearLayout addView

List of usage examples for android.widget LinearLayout addView

Introduction

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

Prototype

public void addView(View child) 

Source Link

Document

Adds a child view.

Usage

From source file:net.networksaremadeofstring.rhybudd.ViewZenossEvent.java

/** Called when the activity is first created. */
@Override//from  w w w.jav  a 2  s.  c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BugSenseHandler.initAndStartSession(ViewZenossEvent.this, "44a76a8c");

    settings = PreferenceManager.getDefaultSharedPreferences(this);

    setContentView(R.layout.view_zenoss_event);

    try {
        actionbar = getActionBar();
        actionbar.setDisplayHomeAsUpEnabled(true);
        actionbar.setHomeButtonEnabled(true);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "OnCreate", e);
    }

    try {
        ((TextView) findViewById(R.id.EventTitle)).setText(getIntent().getStringExtra("Device"));
        ((TextView) findViewById(R.id.Summary)).setText(Html.fromHtml(getIntent().getStringExtra("Summary")));
        ((TextView) findViewById(R.id.LastTime)).setText(getIntent().getStringExtra("LastTime"));
        ((TextView) findViewById(R.id.EventCount))
                .setText("Count: " + Integer.toString(getIntent().getIntExtra("Count", 0)));
    } catch (Exception e) {
        //We don't need to much more than report it because the direct API request will sort it out for us.
        BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "OnCreate", e);
    }

    firstLoadHandler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            try {
                if (EventObject.has("result")
                        && EventObject.getJSONObject("result").getBoolean("success") == true) {
                    //Log.i("Event",EventObject.toString(3));
                    TextView Title = (TextView) findViewById(R.id.EventTitle);
                    TextView Component = (TextView) findViewById(R.id.Componant);
                    TextView EventClass = (TextView) findViewById(R.id.EventClass);
                    TextView Summary = (TextView) findViewById(R.id.Summary);
                    TextView FirstTime = (TextView) findViewById(R.id.FirstTime);
                    TextView LastTime = (TextView) findViewById(R.id.LastTime);
                    LinearLayout logList;

                    EventDetails = EventObject.getJSONObject("result").getJSONArray("event").getJSONObject(0);

                    try {
                        if (EventDetails.getString("eventState").equals("Acknowledged")) {
                            ((ImageView) findViewById(R.id.ackIcon))
                                    .setImageResource(R.drawable.ic_acknowledged);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //Log.e("EventDetails",EventDetails.toString(3));

                    try {
                        Title.setText(EventDetails.getString("device_title"));
                    } catch (Exception e) {
                        Title.setText("Unknown Device - Event Details");
                    }

                    try {
                        Component.setText(EventDetails.getString("component"));
                    } catch (Exception e) {
                        Component.setText("Unknown Component");
                    }

                    try {
                        EventClass.setText(EventDetails.getString("eventClassKey"));
                    } catch (Exception e) {
                        EventClass.setText("Unknown Event Class");
                    }

                    try {
                        ImageView img = (ImageView) findViewById(R.id.summaryImage);

                        URLImageParser p = new URLImageParser(img, ViewZenossEvent.this, Summary);
                        Spanned htmlSpan = Html.fromHtml(EventDetails.getString("message"), p, null);

                        Summary.setText(htmlSpan);
                        //Summary.setText(Html.fromHtml(EventDetails.getString("message")));

                        //((ImageView) findViewById(R.id.summaryImage)).setImageDrawable(p.drawable);
                        //Log.i("Summary",EventDetails.getString("message"));

                        //((TextView) findViewById(R.id.Summary)).setVisibility(View.GONE);
                        //((WebView) findViewById(R.id.summaryWebView)).loadData(EventDetails.getString("message"), "text/html", null);
                        //((WebView) findViewById(R.id.summaryWebView)).loadDataWithBaseURL(null, EventDetails.getString("message"), "text/html", "UTF-8", "about:blank");

                        try {
                            Summary.setMovementMethod(LinkMovementMethod.getInstance());
                        } catch (Exception e) {
                            //Worth a shot
                        }
                    } catch (Exception e) {
                        Summary.setText("No Summary available");
                    }

                    try {
                        FirstTime.setText(EventDetails.getString("firstTime"));
                    } catch (Exception e) {
                        FirstTime.setText("No Start Date Provided");
                    }

                    try {
                        LastTime.setText(EventDetails.getString("stateChange"));
                    } catch (Exception e) {
                        LastTime.setText("No Recent Date Provided");
                    }

                    try {
                        ((TextView) findViewById(R.id.EventCount))
                                .setText("Count: " + EventDetails.getString("count"));
                    } catch (Exception e) {
                        ((TextView) findViewById(R.id.EventCount)).setText("Count: ??");
                    }

                    try {
                        ((TextView) findViewById(R.id.Agent)).setText(EventDetails.getString("agent"));
                    } catch (Exception e) {
                        ((TextView) findViewById(R.id.Agent)).setText("unknown");
                    }

                    try {
                        JSONArray Log = EventDetails.getJSONArray("log");

                        int LogEntryCount = Log.length();

                        logList = (LinearLayout) findViewById(R.id.LogList);

                        if (LogEntryCount == 0) {
                            /*String[] LogEntries = {"No log entries could be found"};
                            ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));*/

                            TextView newLog = new TextView(ViewZenossEvent.this);
                            newLog.setText("No log entries could be found");

                            logList.addView(newLog);
                        } else {
                            LogEntries = new String[LogEntryCount];

                            for (int i = 0; i < LogEntryCount; i++) {
                                //LogEntries[i] = Log.getJSONArray(i).getString(0) + " set " + Log.getJSONArray(i).getString(2) +"\nAt: " + Log.getJSONArray(i).getString(1);

                                TextView newLog = new TextView(ViewZenossEvent.this);
                                newLog.setText(Html.fromHtml("<strong>" + Log.getJSONArray(i).getString(0)
                                        + "</strong> wrote " + Log.getJSONArray(i).getString(2)
                                        + "\n<br/><strong>At:</strong> " + Log.getJSONArray(i).getString(1)));
                                newLog.setPadding(0, 6, 0, 6);
                                logList.addView(newLog);
                            }

                            /*try
                            {
                               ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));
                            }
                            catch(Exception e)
                            {
                               Toast.makeText(getApplicationContext(), "There was an error trying process the log entries for this event.", Toast.LENGTH_SHORT).show();
                            }*/
                        }
                    } catch (Exception e) {
                        TextView newLog = new TextView(ViewZenossEvent.this);
                        newLog.setText("No log entries could be found");
                        newLog.setPadding(0, 6, 0, 6);
                        ((LinearLayout) findViewById(R.id.LogList)).addView(newLog);

                        /*String[] LogEntries = {"No log entries could be found"};
                        try
                        {
                           ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));
                        }
                        catch(Exception e1)
                        {
                           //BugSenseHandler.log("ViewZenossEvent-LogEntries", e1);
                        }*/
                    }
                } else {
                    //Log.e("ViewEvent",EventObject.toString(3));
                    Toast.makeText(ViewZenossEvent.this, "There was an error loading the Event details",
                            Toast.LENGTH_LONG).show();
                    //finish();
                }
            } catch (Exception e) {
                Toast.makeText(ViewZenossEvent.this,
                        "An error was encountered parsing the JSON. An error report has been sent.",
                        Toast.LENGTH_LONG).show();
                //BugSenseHandler.log("ViewZenossEvent", e);
            }
        }
    };

    dialog = new ProgressDialog(this);
    dialog.setTitle("Contacting Zenoss");
    dialog.setMessage("Please wait:\nLoading Event details....");
    dialog.show();
    dataPreload = new Thread() {
        public void run() {
            try {
                /*if(API == null)
                {
                   if(settings.getBoolean("httpBasicAuth", false))
                   {
                      API = new ZenossAPIv2(settings.getString("userName", ""), settings.getString("passWord", ""), settings.getString("URL", ""),settings.getString("BAUser", ""), settings.getString("BAPassword", ""));
                   }
                   else
                   {
                      API = new ZenossAPIv2(settings.getString("userName", ""), settings.getString("passWord", ""), settings.getString("URL", ""));
                   }
                }
                        
                EventObject = API.GetEvent(getIntent().getStringExtra("EventID"));*/

                if (settings.getBoolean(ZenossAPI.PREFERENCE_IS_ZAAS, false)) {
                    API = new ZenossAPIZaas();
                } else {
                    API = new ZenossAPICore();
                }

                ZenossCredentials credentials = new ZenossCredentials(ViewZenossEvent.this);
                API.Login(credentials);
                EventObject = API.GetEvent(getIntent().getStringExtra("EventID"));
            } catch (Exception e) {
                firstLoadHandler.sendEmptyMessage(0);
                BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "DataPreloadThread", e);
            } finally {
                firstLoadHandler.sendEmptyMessage(1);
            }
        }
    };

    dataPreload.start();
}

From source file:com.activiti.android.app.fragments.settings.AccountSettingsFragment.java

private void updateIntegrations() {
    Map<Long, Integration> integrationMap = IntegrationManager.getInstance(getActivity())
            .getByAccountId(accountId);//from w  ww  .j  a  v  a 2s . co m

    // No integration. Display nothing
    if (integrationMap == null || integrationMap.isEmpty()) {
        hide(R.id.settings_intregration_alfresco_parent_container);
        hide(R.id.settings_intregration_alfresco_parent_title);
        return;
    }

    LinearLayout integrationContainer = (LinearLayout) viewById(R.id.settings_intregration_alfresco_container);
    integrationContainer.removeAllViews();
    ThreeLinesViewHolder vh;
    View integrationView;
    int iconId, descriptionId;
    for (Map.Entry<Long, Integration> entry : integrationMap.entrySet()) {
        integrationView = LayoutInflater.from(getActivity()).inflate(R.layout.row_three_lines_caption,
                integrationContainer, false);
        integrationView.setTag(entry.getValue().getProviderId());

        vh = new ThreeLinesViewHolder(integrationView);
        vh.topText.setText(entry.getValue().getName());
        vh.middleText.setText(entry.getValue().getAccountUsername());
        vh.icon.setVisibility(View.VISIBLE);

        switch (entry.getValue().getOpenType()) {
        case Integration.OPEN_NATIVE_APP:
            iconId = R.drawable.alfresco_logo;
            descriptionId = R.string.settings_account_integration_alfresco_mobile;
            break;
        case Integration.OPEN_BROWSER:
            iconId = R.drawable.ic_open_in_browser_grey;
            descriptionId = R.string.settings_account_integration_alfresco_browser;
            break;
        default:
            iconId = R.drawable.ic_wrong_grey;
            descriptionId = R.string.settings_account_integration_alfresco_none;
            break;
        }
        vh.bottomText.setText(descriptionId);
        vh.icon.setImageResource(iconId);
        vh.choose.setVisibility(View.VISIBLE);
        vh.choose.setBackgroundResource(R.drawable.activititheme_list_selector_holo_light);
        vh.choose.setClickable(true);
        vh.choose.setPadding(16, 16, 16, 16);
        vh.choose.setImageResource(R.drawable.ic_more_grey);
        vh.choose.setTag(entry.getValue());
        vh.choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                PopupMenu popup = new PopupMenu(getActivity(), v);
                if (((Integration) v.getTag()).getOpenType() == Integration.OPEN_UNDEFINED) {
                    popup.getMenuInflater().inflate(R.menu.integration_alfresco_add, popup.getMenu());
                } else {
                    popup.getMenuInflater().inflate(R.menu.integration_alfresco_remove, popup.getMenu());
                }
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.integration_alfresco_remove:
                            // Analytics
                            AnalyticsHelper.reportOperationEvent(getActivity(),
                                    AnalyticsManager.CATEGORY_SETTINGS,
                                    AnalyticsManager.ACTION_ALFRESCO_INTEGRATION, AnalyticsManager.LABEL_REMOVE,
                                    1, false);

                            IntegrationManager.getInstance(getActivity())
                                    .update(((Integration) v.getTag()).getProviderId(), -1l, null, null);
                            updateIntegrations();
                            break;
                        case R.id.integration_alfresco_mobile:
                            // Analytics
                            AnalyticsHelper.reportOperationEvent(getActivity(),
                                    AnalyticsManager.CATEGORY_SETTINGS,
                                    AnalyticsManager.ACTION_ALFRESCO_INTEGRATION,
                                    AnalyticsManager.LABEL_LINK_MOBILE, 1, false);

                            AlfrescoIntegrationFragment.with(getActivity())
                                    .integrationProviverId(((Integration) v.getTag()).getProviderId())
                                    .accountId(accountId).display();
                            break;
                        case R.id.integration_alfresco_web:
                            // Analytics
                            AnalyticsHelper.reportOperationEvent(getActivity(),
                                    AnalyticsManager.CATEGORY_SETTINGS,
                                    AnalyticsManager.ACTION_ALFRESCO_INTEGRATION,
                                    AnalyticsManager.LABEL_LINK_WEB, 1, false);

                            IntegrationManager.getInstance(getActivity()).update(
                                    ((Integration) v.getTag()).getProviderId(),
                                    IntegrationSchema.COLUMN_OPEN_TYPE, Integration.OPEN_BROWSER);
                            updateIntegrations();
                            break;
                        }
                        return true;
                    }
                });

                popup.show(); // showing popup menu
            }
        });
        integrationContainer.addView(integrationView);
    }
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InlinedApi")
private void openGridGallery() {
    final int tnSize = resources.getDimensionPixelSize(R.dimen.post_thumbnail_size);

    class GridGalleryAdapter extends ArrayAdapter<Triple<AttachmentModel, String, String>>
            implements View.OnClickListener, AbsListView.OnScrollListener {
        private final GridView view;
        private boolean selectingMode = false;
        private boolean[] isSelected = null;
        private volatile boolean isBusy = false;

        public GridGalleryAdapter(GridView view, List<Triple<AttachmentModel, String, String>> list) {
            super(activity, 0, list);
            this.view = view;
            this.isSelected = new boolean[list.size()];
        }//from   www .  j a v  a 2 s. c om

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                if (isBusy)
                    setNonBusy();
                isBusy = false;
            } else
                isBusy = true;
        }

        private void setNonBusy() {
            if (!downloadThumbnails())
                return;
            for (int i = 0; i < view.getChildCount(); ++i) {
                View v = view.getChildAt(i);
                Object tnTag = v.findViewById(R.id.post_thumbnail_image).getTag();
                if (tnTag == null || tnTag == Boolean.FALSE)
                    fill(view.getPositionForView(v), v, false);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new FrameLayout(activity);
                convertView.setLayoutParams(new AbsListView.LayoutParams(tnSize, tnSize));
                ImageView tnImage = new ImageView(activity);
                tnImage.setLayoutParams(new FrameLayout.LayoutParams(tnSize, tnSize, Gravity.CENTER));
                tnImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                tnImage.setId(R.id.post_thumbnail_image);
                ((FrameLayout) convertView).addView(tnImage);
            }
            convertView.setTag(getItem(position).getLeft());
            safeRegisterForContextMenu(convertView);
            convertView.setOnClickListener(this);
            fill(position, convertView, isBusy);
            if (isSelected[position]) {
                /*ImageView overlay = new ImageView(activity);
                overlay.setImageResource(android.R.drawable.checkbox_on_background);*/
                FrameLayout overlay = new FrameLayout(activity);
                overlay.setBackgroundColor(Color.argb(128, 0, 255, 0));
                if (((FrameLayout) convertView).getChildCount() < 2)
                    ((FrameLayout) convertView).addView(overlay);

            } else {
                if (((FrameLayout) convertView).getChildCount() > 1)
                    ((FrameLayout) convertView).removeViewAt(1);
            }
            return convertView;
        }

        private void safeRegisterForContextMenu(View view) {
            try {
                view.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                        if (presentationModel == null) {
                            Fragment currentFragment = MainApplication
                                    .getInstance().tabsSwitcher.currentFragment;
                            if (currentFragment instanceof BoardFragment) {
                                currentFragment.onCreateContextMenu(menu, v, menuInfo);
                            }
                        } else {
                            BoardFragment.this.onCreateContextMenu(menu, v, menuInfo);
                        }
                    }
                });
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }

        @Override
        public void onClick(View v) {
            if (selectingMode) {
                int position = view.getPositionForView(v);
                isSelected[position] = !isSelected[position];
                notifyDataSetChanged();
            } else {
                BoardFragment fragment = BoardFragment.this;
                if (presentationModel == null) {
                    Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                    if (currentFragment instanceof BoardFragment)
                        fragment = (BoardFragment) currentFragment;
                }
                fragment.openAttachment((AttachmentModel) v.getTag());
            }
        }

        private void fill(int position, View view, boolean isBusy) {
            AttachmentModel attachment = getItem(position).getLeft();
            String attachmentHash = getItem(position).getMiddle();
            ImageView tnImage = (ImageView) view.findViewById(R.id.post_thumbnail_image);
            if (attachment.thumbnail == null || attachment.thumbnail.length() == 0) {
                tnImage.setTag(Boolean.TRUE);
                tnImage.setImageResource(Attachments.getDefaultThumbnailResId(attachment.type));
                return;
            }
            tnImage.setTag(Boolean.FALSE);
            CancellableTask imagesDownloadTask = BoardFragment.this.imagesDownloadTask;
            ExecutorService imagesDownloadExecutor = BoardFragment.this.imagesDownloadExecutor;
            if (presentationModel == null) {
                Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                if (currentFragment instanceof BoardFragment) {
                    imagesDownloadTask = ((BoardFragment) currentFragment).imagesDownloadTask;
                    imagesDownloadExecutor = ((BoardFragment) currentFragment).imagesDownloadExecutor;
                }
            }
            bitmapCache.asyncGet(attachmentHash, attachment.thumbnail, tnSize, chan, localFile,
                    imagesDownloadTask, tnImage, imagesDownloadExecutor, Async.UI_HANDLER,
                    downloadThumbnails() && !isBusy,
                    downloadThumbnails() ? (isBusy ? 0 : R.drawable.thumbnail_error)
                            : Attachments.getDefaultThumbnailResId(attachment.type));
        }

        public void setSelectingMode(boolean selectingMode) {
            this.selectingMode = selectingMode;
            if (!selectingMode) {
                Arrays.fill(isSelected, false);
                notifyDataSetChanged();
            }
        }

        public void selectAll() {
            if (selectingMode) {
                Arrays.fill(isSelected, true);
                notifyDataSetChanged();
            }
        }

        public void downloadSelected(final Runnable onFinish) {
            final Dialog progressDialog = ProgressDialog.show(activity,
                    resources.getString(R.string.grid_gallery_dlg_title),
                    resources.getString(R.string.grid_gallery_dlg_message), true, false);
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    BoardFragment fragment = BoardFragment.this;
                    if (fragment.presentationModel == null) {
                        Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                        if (currentFragment instanceof BoardFragment)
                            fragment = (BoardFragment) currentFragment;
                    }
                    boolean flag = false;
                    for (int i = 0; i < isSelected.length; ++i)
                        if (isSelected[i])
                            if (!fragment.downloadFile(getItem(i).getLeft(), true))
                                flag = true;
                    final boolean toast = flag;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (toast)
                                Toast.makeText(activity, R.string.notification_download_exists_or_in_queue,
                                        Toast.LENGTH_LONG).show();
                            progressDialog.dismiss();
                            onFinish.run();
                        }
                    });
                }
            });
        }
    }

    try {
        List<Triple<AttachmentModel, String, String>> list = presentationModel.getAttachments();
        if (list == null) {
            Toast.makeText(activity, R.string.notifacation_updating_now, Toast.LENGTH_LONG).show();
            return;
        }

        GridView grid = new GridView(activity);
        final GridGalleryAdapter gridAdapter = new GridGalleryAdapter(grid, list);
        grid.setNumColumns(GridView.AUTO_FIT);
        grid.setColumnWidth(tnSize);
        int spacing = (int) (resources.getDisplayMetrics().density * 5 + 0.5f);
        grid.setVerticalSpacing(spacing);
        grid.setHorizontalSpacing(spacing);
        grid.setPadding(spacing, spacing, spacing, spacing);
        grid.setAdapter(gridAdapter);
        grid.setOnScrollListener(gridAdapter);
        grid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));

        final Button btnToSelecting = new Button(activity);
        btnToSelecting.setText(R.string.grid_gallery_select);
        CompatibilityUtils.setTextAppearance(btnToSelecting, android.R.style.TextAppearance_Small);
        btnToSelecting.setSingleLine();
        btnToSelecting.setVisibility(View.VISIBLE);
        btnToSelecting.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        final LinearLayout layoutSelectingButtons = new LinearLayout(activity);
        layoutSelectingButtons.setOrientation(LinearLayout.HORIZONTAL);
        layoutSelectingButtons.setWeightSum(10f);
        Button btnDownload = new Button(activity);
        btnDownload.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.25f));
        btnDownload.setText(R.string.grid_gallery_download);
        CompatibilityUtils.setTextAppearance(btnDownload, android.R.style.TextAppearance_Small);
        btnDownload.setSingleLine();
        Button btnSelectAll = new Button(activity);
        btnSelectAll.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.75f));
        btnSelectAll.setText(android.R.string.selectAll);
        CompatibilityUtils.setTextAppearance(btnSelectAll, android.R.style.TextAppearance_Small);
        btnSelectAll.setSingleLine();
        Button btnCancel = new Button(activity);
        btnCancel.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
        btnCancel.setText(android.R.string.cancel);
        CompatibilityUtils.setTextAppearance(btnCancel, android.R.style.TextAppearance_Small);
        btnCancel.setSingleLine();
        layoutSelectingButtons.addView(btnDownload);
        layoutSelectingButtons.addView(btnSelectAll);
        layoutSelectingButtons.addView(btnCancel);
        layoutSelectingButtons.setVisibility(View.GONE);
        layoutSelectingButtons.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        btnToSelecting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.GONE);
                layoutSelectingButtons.setVisibility(View.VISIBLE);
                gridAdapter.setSelectingMode(true);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.VISIBLE);
                layoutSelectingButtons.setVisibility(View.GONE);
                gridAdapter.setSelectingMode(false);
            }
        });

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

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridAdapter.downloadSelected(new Runnable() {
                    @Override
                    public void run() {
                        btnToSelecting.setVisibility(View.VISIBLE);
                        layoutSelectingButtons.setVisibility(View.GONE);
                        gridAdapter.setSelectingMode(false);
                    }
                });
            }
        });

        LinearLayout dlgLayout = new LinearLayout(activity);
        dlgLayout.setOrientation(LinearLayout.VERTICAL);
        dlgLayout.addView(btnToSelecting);
        dlgLayout.addView(layoutSelectingButtons);
        dlgLayout.addView(grid);

        Dialog gridDialog = new Dialog(activity);
        gridDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        gridDialog.setContentView(dlgLayout);
        gridDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        gridDialog.show();
    } catch (OutOfMemoryError oom) {
        MainApplication.freeMemory();
        Logger.e(TAG, oom);
        Toast.makeText(activity, R.string.error_out_of_memory, Toast.LENGTH_LONG).show();
    }
}

From source file:com.android.launcher3.Launcher.java

@Override
public boolean onLongClick(View v) {
    if (!isDraggingEnabled())
        return false;
    if (isWorkspaceLocked())
        return false;
    if (mState != State.WORKSPACE)
        return false;

    if (creation != null)
        creation.clearAllLayout();//www  .j a  v  a 2  s. c  o m

    if ((FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP && v instanceof PageIndicator)
            || (v == mAllAppsButton && mAllAppsButton != null)) {
        onLongClickAllAppsButton(v);
        return true;
    }

    if (v instanceof Workspace) {
        if (!mWorkspace.isInOverviewMode()) {
            if (!mWorkspace.isTouchActive()) {
                showOverviewMode(true);
                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    CellLayout.CellInfo longClickCellInfo = null;
    View itemUnderLongClick = null;
    if (v.getTag() instanceof ItemInfo) {
        ItemInfo info = (ItemInfo) v.getTag();
        longClickCellInfo = new CellLayout.CellInfo(v, info);
        itemUnderLongClick = longClickCellInfo.cell;
        mPendingRequestArgs = null;
    }

    // The hotseat touch handling does not go through Workspace, and we always allow long press
    // on hotseat items.
    if (!mDragController.isDragging()) {
        if (itemUnderLongClick == null) {
            // User long pressed on empty space
            mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
                    HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
            if (mWorkspace.isInOverviewMode()) {
                mWorkspace.startReordering(v);
            } else {
                showOverviewMode(true);
            }
        } else {
            final boolean isAllAppsButton = !FeatureFlags.NO_ALL_APPS_ICON && isHotseatLayout(v)
                    && mDeviceProfile.inv.isAllAppsButtonRank(
                            mHotseat.getOrderInHotseat(longClickCellInfo.cellX, longClickCellInfo.cellY));
            if (!(itemUnderLongClick instanceof Folder || isAllAppsButton)) {
                // User long pressed on an item
                DragOptions dragOptions = new DragOptions();
                if (itemUnderLongClick instanceof BubbleTextView) {
                    BubbleTextView icon = (BubbleTextView) itemUnderLongClick;
                    if (icon.hasDeepShortcuts()) {
                        DeepShortcutsContainer dsc = DeepShortcutsContainer.showForIcon(icon);
                        if (dsc != null) {
                            dragOptions.deferDragCondition = dsc.createDeferDragCondition(null);
                        }
                    }
                }

                int positionInGrid = mHotseat.getOrderInHotseat(longClickCellInfo.cellX,
                        longClickCellInfo.cellY);

                List<Shortcuts> shortcutses = new ArrayList<Shortcuts>();

                if (creation != null)
                    creation.clearAllLayout();

                mWorkspace.startDrag(longClickCellInfo, dragOptions);

                //Get selected app info
                final Object tag = v.getTag();
                final ShortcutInfo shortcut;
                try {
                    shortcut = (ShortcutInfo) tag;
                    Drawable icon;
                    if (Utilities.loadBitmapPref(Launcher.getLauncherActivity(),
                            shortcut.getTargetComponent().getPackageName()) != null) {
                        icon = new BitmapDrawable(activity.getResources(), Utilities.loadBitmapPref(activity,
                                shortcut.getTargetComponent().getPackageName()));
                    } else {
                        icon = new BitmapDrawable(activity.getResources(),
                                shortcut.getIcon(new IconCache(Launcher.this, getDeviceProfile().inv)));
                    }

                    shortcutses = ShortcutsManager.getShortcutsBasedOnTag(Launcher.this.getApplicationContext(),
                            Launcher.this, shortcut, icon);
                    ShortcutsBuilder builder = new ShortcutsBuilder.Builder(this, masterLayout)
                            .launcher3Shortcuts(gridSize, positionInGrid, (int) v.getY(), v.getBottom(),
                                    Hotseat.isHotseatTouched,
                                    Utilities.getDockSizeDefaultValue(getApplicationContext()))
                            .setOptionLayoutStyle(StyleOption.NONE).setPackageImage(icon)
                            .setShortcutsList(shortcutses).build();

                    creation = new ShortcutsCreation(builder);

                    creation.init();

                    Hotseat.isHotseatTouched = false;

                } catch (ClassCastException e) {
                    Log.e(TAG, "Clicked on Folder/Widget!");
                    positionInGrid = mHotseat.getOrderInHotseat(longClickCellInfo.cellX,
                            longClickCellInfo.cellY);
                    try {
                        //Get selected folder info
                        final View f = v;
                        final Object tagF = v.getTag();
                        final FolderInfo folder;
                        folder = (FolderInfo) tagF;

                        shortcutses = new ArrayList<Shortcuts>();
                        shortcutses.add(new Shortcuts(R.drawable.ic_folder_open_black_24dp,
                                getString(R.string.folder_open), new OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (f instanceof FolderIcon) {
                                            onClickFolderIcon(f);
                                            creation.clearAllLayout();
                                        }
                                    }
                                }));
                        shortcutses.add(new Shortcuts(R.drawable.ic_title_black_24dp,
                                getString(R.string.folder_rename), new OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (f instanceof FolderIcon) {
                                            AlertDialog.Builder alert = new AlertDialog.Builder(
                                                    new ContextThemeWrapper(Launcher.this,
                                                            R.style.AlertDialogCustom));
                                            LinearLayout layout = new LinearLayout(getApplicationContext());
                                            layout.setOrientation(LinearLayout.VERTICAL);
                                            layout.setPadding(100, 50, 100, 100);

                                            final EditText titleBox = new EditText(Launcher.this);

                                            titleBox.getBackground().mutate()
                                                    .setColorFilter(
                                                            ContextCompat.getColor(getApplicationContext(),
                                                                    R.color.colorPrimary),
                                                            PorterDuff.Mode.SRC_ATOP);
                                            alert.setMessage(getString(R.string.folder_title));
                                            alert.setTitle(getString(R.string.folder_enter_title));

                                            layout.addView(titleBox);
                                            alert.setView(layout);

                                            alert.setPositiveButton(getString(R.string.ok),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog,
                                                                int whichButton) {
                                                            folder.setTitle(titleBox.getText().toString());
                                                            LauncherModel.updateItemInDatabase(
                                                                    Launcher.getLauncherActivity(), folder);
                                                        }
                                                    });

                                            alert.setNegativeButton(getString(R.string.cancel),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog,
                                                                int whichButton) {
                                                            creation.clearAllLayout();
                                                        }
                                                    });
                                            alert.show();
                                            creation.clearAllLayout();
                                        }
                                    }
                                }));

                        ShortcutsBuilder builder = new ShortcutsBuilder.Builder(this, masterLayout)
                                .launcher3Shortcuts(gridSize, positionInGrid, (int) v.getY(), v.getBottom(),
                                        Hotseat.isHotseatTouched,
                                        Utilities.getDockSizeDefaultValue(getApplicationContext()))
                                .setOptionLayoutStyle(0)
                                .setPackageImage(
                                        ContextCompat.getDrawable(Launcher.this, R.mipmap.ic_launcher_home))
                                .setShortcutsList(shortcutses).build();

                        creation = new ShortcutsCreation(builder);

                        creation.init();
                    } catch (ClassCastException ee) {
                    }
                }
            }
        }
    }
    return true;
}

From source file:com.nest5.businessClient.Initialactivity.java

@Override
public void OnHomeObjectFragmentCreated(View v) {
    // TODO Auto-generated method stub
    LinearLayout ll = (LinearLayout) v.findViewById(R.id.ingredient_categories_buttons);
    ll.removeAllViews();/*www  .ja  va 2s  .  c o  m*/
    String values[] = { "Combos", "Productos", "Ingredientes", "+Vendido", "Nuevo" };

    for (int i = 0; i < values.length; i++) {

        Button btnTag = (Button) getLayoutInflater().inflate(R.layout.template_button, null);
        btnTag.setText((values[i]));
        btnTag.setId(i);
        btnTag.setOnClickListener(typeButtonClickListener);
        ll.addView(btnTag);

    }
    SharedPreferences defaultprefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean layouttables = defaultprefs.getBoolean("arrange_tables", false);

    itemsView = (GridView) v.findViewById(R.id.gridview);
    statusText = (TextView) v.findViewById(R.id.group_owner);
    deviceText = (TextView) v.findViewById(R.id.device_info);
    saleValue = (TextView) v.findViewById(R.id.sale_info);
    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_registrable);
    if (layouttables) {
        statusText.setVisibility(View.VISIBLE);
        //statusText.setText("No hay Mesa Seleccionada.");
    } else {
        statusText.setVisibility(View.INVISIBLE);
        statusText.setText("");
    }
    updateSaleValue();
    pagarButton = (Button) v.findViewById(R.id.pay_register);
    guardarButton = (Button) v.findViewById(R.id.save_register);
    pagarButton.setOnClickListener(payListener);
    guardarButton.setOnClickListener(saveListener);
    registerList = new ArrayList<Registrable>();
    gridAdapter = new ImageAdapter(mContext, registerList, inflater, gridButtonListener);
    setGridContent(gridAdapter, comboList);
    ArrayList<String> registrables = new ArrayList<String>();
    for (Registrable actual : allRegistrables) {
        registrables.add(actual.name);
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, registrables);
    autoCompleteTextView.setAdapter(adapter);
    autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            String selection = (String) parent.getItemAtPosition(position);
            int pos = -1;

            for (int i = 0; i < allRegistrables.size(); i++) {
                if (allRegistrables.get(i).name.equalsIgnoreCase(selection)) {
                    pos = i;
                    break;
                }
            }
            if (pos > -1) {
                if (currentOrder.containsKey(allRegistrables.get(pos))) {
                    currentOrder.put(allRegistrables.get(pos), currentOrder.get(allRegistrables.get(pos)) + 1);

                } else {
                    currentOrder.put(allRegistrables.get(pos), 1);
                }
                makeTable(allRegistrables.get(pos).name);
            } else {
                Toast.makeText(mContext, "No Existe el tem", Toast.LENGTH_LONG).show();
            }
            autoCompleteTextView.setText("");
            autoCompleteTextView.setHint("Buscar tems para Registrar");

        }

    });
    autoCompleteTextView.setText("");
    autoCompleteTextView.setHint("Buscar tems para Registrar");
    // Tomar la tabla de la izquierda del home view
    table = (TableLayout) v.findViewById(R.id.my_table);
    makeTable("NA");

    deviceText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mTCPPrint != null) {
                mTCPPrint.stopClient();
            }
            new connectTask().execute("");

        }
    });

}

From source file:cm.aptoide.pt.MainActivity.java

private void loadUItopapps() {
    ((ToggleButton) featuredView.findViewById(R.id.toggleButton1)).setOnCheckedChangeListener(null);
    Cursor c = db.getFeaturedTopApps();

    values = new ArrayList<HashMap<String, String>>();
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("name", c.getString(1));
        item.put("icon", db.getIconsPath(0, Category.TOPFEATURED) + c.getString(4));
        item.put("rating", c.getString(5));
        item.put("id", c.getString(0));
        item.put("apkid", c.getString(7));
        item.put("vercode", c.getString(8));
        item.put("vername", c.getString(2));
        item.put("downloads", c.getString(6));
        if (values.size() == 26) {
            break;
        }/*from  ww  w .  j ava2s  .c  o  m*/
        values.add(item);
    }
    c.close();

    runOnUiThread(new Runnable() {

        public void run() {

            LinearLayout ll = (LinearLayout) featuredView.findViewById(R.id.container);
            ll.removeAllViews();
            LinearLayout llAlso = new LinearLayout(MainActivity.this);
            llAlso.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            llAlso.setOrientation(LinearLayout.HORIZONTAL);
            for (int i = 0; i != values.size(); i++) {
                LinearLayout txtSamItem = (LinearLayout) getLayoutInflater().inflate(R.layout.row_grid_item,
                        null);
                ((TextView) txtSamItem.findViewById(R.id.name)).setText(values.get(i).get("name"));
                // ((TextView) txtSamItem.findViewById(R.id.version))
                // .setText(getString(R.string.version) +" "+
                // values.get(i).get("vername"));
                ((TextView) txtSamItem.findViewById(R.id.downloads)).setText(
                        "(" + values.get(i).get("downloads") + " " + getString(R.string.downloads) + ")");
                String hashCode = (values.get(i).get("apkid") + "|" + values.get(i).get("vercode")) + "";
                cm.aptoide.com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(
                        values.get(i).get("icon"), (ImageView) txtSamItem.findViewById(R.id.icon), hashCode);

                // imageLoader.DisplayImage(-1, values.get(i).get("icon"),
                // (ImageView) txtSamItem.findViewById(R.id.icon),
                // mContext);
                float stars = 0f;
                try {
                    stars = Float.parseFloat(values.get(i).get("rating"));
                } catch (Exception e) {
                    stars = 0f;
                }
                ((RatingBar) txtSamItem.findViewById(R.id.rating)).setRating(stars);
                ((RatingBar) txtSamItem.findViewById(R.id.rating)).setIsIndicator(true);
                txtSamItem.setPadding(10, 0, 0, 0);
                txtSamItem.setTag(values.get(i).get("id"));
                txtSamItem.setLayoutParams(
                        new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100, 1));
                // txtSamItem.setOnClickListener(featuredListener);
                txtSamItem.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent i = new Intent(MainActivity.this, ApkInfo.class);
                        long id = Long.parseLong((String) arg0.getTag());
                        i.putExtra("_id", id);
                        i.putExtra("top", true);
                        i.putExtra("category", Category.TOPFEATURED.ordinal());
                        startActivity(i);
                    }
                });

                txtSamItem.measure(0, 0);

                if (i % 2 == 0) {
                    ll.addView(llAlso);

                    llAlso = new LinearLayout(MainActivity.this);
                    llAlso.setLayoutParams(
                            new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100));
                    llAlso.setOrientation(LinearLayout.HORIZONTAL);
                    llAlso.addView(txtSamItem);
                } else {
                    llAlso.addView(txtSamItem);
                }
            }

            ll.addView(llAlso);
            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            // System.out.println(sPref.getString("app_rating",
            // "All").equals(
            // "Mature"));
            ((ToggleButton) featuredView.findViewById(R.id.toggleButton1))
                    .setChecked(!sPref.getBoolean("matureChkBox", false));
            ((ToggleButton) featuredView.findViewById(R.id.toggleButton1))
                    .setOnCheckedChangeListener(adultCheckedListener);
        }
    });
}

From source file:com.gh4a.IssueLabelListActivity.java

private void fillData() {
    final Typeface condensed = getApplicationContext().condensed;
    LinearLayout ll = (LinearLayout) findViewById(R.id.main_content);
    ll.removeAllViews();//from  w ww  .  j  a va 2 s  .  co m

    mAllLabelLayout = new ArrayList<Map<String, Object>>();
    for (final Label label : mLabels) {
        Map<String, Object> selectedLabelItems = new HashMap<String, Object>();
        selectedLabelItems.put("label", label);

        final View rowView = getLayoutInflater().inflate(R.layout.row_issue_label, null);
        final View viewColor = (View) rowView.findViewById(R.id.view_color);

        final LinearLayout llEdit = (LinearLayout) rowView.findViewById(R.id.ll_edit);
        selectedLabelItems.put("llEdit", llEdit);

        final EditText etLabel = (EditText) rowView.findViewById(R.id.et_label);
        selectedLabelItems.put("etLabel", etLabel);

        final TextView tvLabel = (TextView) rowView.findViewById(R.id.tv_title);
        selectedLabelItems.put("tvLabel", tvLabel);

        tvLabel.setTypeface(condensed);
        tvLabel.setText(label.getName());

        viewColor.setBackgroundColor(Color.parseColor("#" + label.getColor()));
        selectedLabelItems.put("viewColor", viewColor);
        mAllLabelLayout.add(selectedLabelItems);

        viewColor.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (llEdit.getVisibility() == View.VISIBLE) {
                    llEdit.setVisibility(View.GONE);
                    unselectLabel(tvLabel, viewColor, label.getColor());
                } else {
                    llEdit.setVisibility(View.VISIBLE);
                    selectLabel(tvLabel, viewColor, label.getColor(), true, etLabel);
                    etLabel.setText(label.getName());
                    mActionMode = startActionMode(new EditActionMode(label.getName(), etLabel));
                }
            }
        });

        tvLabel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout llEdit = (LinearLayout) rowView.findViewById(R.id.ll_edit);
                if (llEdit.getVisibility() == View.VISIBLE) {
                    llEdit.setVisibility(View.GONE);
                    unselectLabel(tvLabel, viewColor, label.getColor());
                } else {
                    llEdit.setVisibility(View.VISIBLE);
                    selectLabel(tvLabel, viewColor, label.getColor(), true, etLabel);
                    etLabel.setText(label.getName());
                    mActionMode = startActionMode(new EditActionMode(label.getName(), etLabel));
                }
            }
        });

        if (!StringUtils.isBlank(mSelectedLabel) && mSelectedLabel.equals(label.getName())) {
            selectLabel(tvLabel, viewColor, label.getColor(), false, etLabel);
            llEdit.setVisibility(View.VISIBLE);
            etLabel.setText(label.getName());
        }

        final View color1 = (View) rowView.findViewById(R.id.color_444444);
        color1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color1.getTag(), false, etLabel);
            }
        });

        final View color2 = (View) rowView.findViewById(R.id.color_02d7e1);
        color2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color2.getTag(), false, etLabel);
            }
        });

        final View color3 = (View) rowView.findViewById(R.id.color_02e10c);
        color3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color3.getTag(), false, etLabel);
            }
        });

        final View color4 = (View) rowView.findViewById(R.id.color_0b02e1);
        color4.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color4.getTag(), false, etLabel);
            }
        });

        final View color5 = (View) rowView.findViewById(R.id.color_d7e102);
        color5.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color5.getTag(), false, etLabel);
            }
        });

        final View color6 = (View) rowView.findViewById(R.id.color_DDDDDD);
        color6.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color6.getTag(), false, etLabel);
            }
        });

        final View color7 = (View) rowView.findViewById(R.id.color_e102d8);
        color7.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color7.getTag(), false, etLabel);
            }
        });

        final View color8 = (View) rowView.findViewById(R.id.color_e10c02);
        color8.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLabel(tvLabel, viewColor, (String) color8.getTag(), false, etLabel);
            }
        });

        ll.addView(rowView);
    }
}

From source file:mobi.monaca.framework.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*ww  w  .  j  av a  2 s .  co m*/
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setImageResource(R.drawable.childbroswer_icon_arrow_left);
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setImageResource(R.drawable.childbroswer_icon_arrow_right);
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setImageResource(R.drawable.childbroswer_icon_close);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            //TODO check LocalFileBootloader
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.mdlive.sav.MDLiveProviderDetails.java

public void handleDateResponse(JSONObject response) {
    horizontalscrollview.setVisibility(View.GONE);
    //Fetch Data From the Services
    JsonParser parser = new JsonParser();
    JsonObject responObj = (JsonObject) parser.parse(response.toString());
    JsonObject profileobj = responObj.get("doctor_profile").getAsJsonObject();

    JsonObject appointment_slot = profileobj.get("appointment_slot").getAsJsonObject();
    JsonArray available_hour = appointment_slot.get("available_hour").getAsJsonArray();

    LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
    String str_timeslot = "", str_phys_avail_id = "";
    if (layout.getChildCount() > 0) {
        layout.removeAllViews();//from w  w w . ja v a  2s.  c o m
    }
    timeSlotListMap.clear();

    for (int i = 0; i < available_hour.size(); i++) {
        JsonObject availabilityStatus = available_hour.get(i).getAsJsonObject();
        String str_availabilityStatus = "";

        if (MdliveUtils.checkJSONResponseHasString(availabilityStatus, "status")) {
            str_availabilityStatus = availabilityStatus.get("status").getAsString();
            if (str_availabilityStatus.equals("Available")) {
                //This visibility is for future timeslots response for the corresponding date selection.
                //if  the future date has timeslots then make an appointment req layout nd textview visibility will be gone

                findViewById(R.id.noappmtsTxtLayout).setVisibility(View.GONE);
                reqfutureapptBtnLayout.setVisibility(View.GONE);
                JsonArray timeSlotArray = availabilityStatus.get("time_slot").getAsJsonArray();

                for (int j = 0; j < timeSlotArray.size(); j++) {
                    JsonObject timeSlotObj = timeSlotArray.get(j).getAsJsonObject();

                    if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "appointment_type")
                            && MdliveUtils.checkJSONResponseHasString(timeSlotObj, "timeslot")) {
                        str_appointmenttype = timeSlotObj.get("appointment_type").getAsString();
                        str_timeslot = timeSlotObj.get("timeslot").getAsString();
                        selectedTimestamp = timeSlotObj.get("timeslot").getAsString();

                        if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "phys_availability_id")) {
                            str_phys_avail_id = timeSlotObj.get("phys_availability_id").getAsString();
                        } else {
                            str_phys_avail_id = null;
                        }

                        HashMap<String, String> datemap = new HashMap<String, String>();
                        datemap.put("timeslot", str_timeslot);
                        datemap.put("phys_id", str_phys_avail_id);
                        datemap.put("appointment_type", str_appointmenttype);
                        videophoneparentLl.setVisibility(View.VISIBLE);
                        timeSlotListMap.add(datemap);

                        final Button myText = new Button(MDLiveProviderDetails.this);

                        if (str_timeslot.equals("0")) {
                            final int density = (int) getBaseContext().getResources()
                                    .getDisplayMetrics().density;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                myText.setElevation(0f);
                            }
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            params.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                            myText.setLayoutParams(params);
                            myText.setGravity(Gravity.CENTER);
                            myText.setTextColor(Color.WHITE);
                            myText.setTextSize(16);
                            myText.setPadding(8 * density, 4 * density, 8 * density, 4 * density);
                            myText.setBackgroundResource(R.drawable.timeslot_white_rounded_corner);
                            myText.setText("Now");
                            myText.setBackgroundResource(R.drawable.timeslot_blue_rounded_corner);
                            myText.setClickable(true);
                            previousSelectedTv = myText;
                            if (str_appointmenttype.toLowerCase().contains("video")
                                    || str_appointmenttype.toLowerCase().contains("video or phone")) {
                                videoList.add(myText);
                            }
                            if (str_appointmenttype.toLowerCase().contains("phone")) {
                                phoneList.add(myText);
                            }

                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            lp.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                            myText.setLayoutParams(lp);
                            myText.setTag("Now");
                            defaultNowTextPreferences(myText, str_appointmenttype);
                            selectedTimeslot = true;
                            clickEventForHorizontalText(myText, str_timeslot, str_phys_avail_id);
                            layout.addView(myText);
                        } else {
                            setHorizontalScrollviewTimeslots(layout, str_timeslot, j, str_phys_avail_id);
                        }
                    }
                }
            } else {
                if (layout.getChildCount() == 0) {
                    selectedTimeslot = false;
                    findViewById(R.id.noappmtsTxtLayout).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.noAppmtsTxt))
                            .setText(getString(R.string.mdl_notimeslots_txt));
                    reqfutureapptBtnLayout.setVisibility(viewsVisibility);
                    ((TextView) findViewById(R.id.reqfutureapptBtn)).setText("Make an appointment request");
                    ((TextView) findViewById(R.id.reqfutureapptBtn)).setTextColor(Color.parseColor("#0079FD"));
                    videophoneparentLl.setVisibility(View.GONE);
                    tapReqFutureBtnAction();
                    findViewById(R.id.reqApmtBtm).setVisibility(View.GONE);
                }
            }
        }
    }

}