Example usage for android.widget LinearLayout setVisibility

List of usage examples for android.widget LinearLayout setVisibility

Introduction

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

Prototype

@RemotableViewMethod
public void setVisibility(@Visibility int visibility) 

Source Link

Document

Set the visibility state of this view.

Usage

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

private void scanRemoteNetwork(final Dialog dialog, final ListView lv_ipaddr,
        final AdapterScanAddressResultList adap, final ArrayList<ScanAddressResultListItem> ipAddressList,
        final String subnet, final int begin_addr, final int end_addr, final NotifyEvent p_ntfy) {
    final Handler handler = new Handler();
    final ThreadCtrl tc = new ThreadCtrl();
    final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_scan_address);
    final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_progress);
    final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_remote_ntwk_progress_msg);
    final Button btn_scan = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_ok);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_cancel);
    final Button scan_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_progress_cancel);

    final CheckedTextView ctv_use_port_number = (CheckedTextView) dialog
            .findViewById(R.id.scan_remote_ntwk_ctv_use_port);
    final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_remote_ntwk_port_number);

    tvmsg.setText("");
    scan_cancel.setText(R.string.msgs_scan_progress_spin_dlg_addr_cancel);
    ll_addr.setVisibility(LinearLayout.GONE);
    ll_prog.setVisibility(LinearLayout.VISIBLE);
    btn_scan.setVisibility(Button.GONE);
    btn_cancel.setVisibility(Button.GONE);
    adap.setButtonEnabled(false);//w  ww  . ja v a  2  s.  co m
    scan_cancel.setEnabled(true);
    dialog.setOnKeyListener(new DialogBackKeyListener(mContext));
    dialog.setCancelable(false);
    // CANCEL?
    scan_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            scan_cancel.setText(mContext.getString(R.string.msgs_progress_dlg_canceling));
            scan_cancel.setEnabled(false);
            util.addDebugMsg(1, "W", "IP Address list creation was cancelled");
            tc.setDisabled();
        }
    });
    dialog.show();

    util.addDebugMsg(1, "I", "Scan IP address ransge is " + subnet + "." + begin_addr + " - " + end_addr);

    final String scan_prog = mContext.getString(R.string.msgs_ip_address_scan_progress);
    String p_txt = String.format(scan_prog, 0);
    tvmsg.setText(p_txt);

    new Thread(new Runnable() {
        @Override
        public void run() {//non UI thread
            mScanCompleteCount = 0;
            mScanAddrCount = end_addr - begin_addr + 1;
            int scan_thread = 60;
            String scan_port = "";
            if (ctv_use_port_number.isChecked())
                scan_port = et_port_number.getText().toString();
            for (int i = begin_addr; i <= end_addr; i += scan_thread) {
                if (!tc.isEnabled())
                    break;
                boolean scan_end = false;
                for (int j = i; j < (i + scan_thread); j++) {
                    if (j <= end_addr) {
                        startRemoteNetworkScanThread(handler, tc, dialog, p_ntfy, lv_ipaddr, adap, tvmsg,
                                subnet + "." + j, ipAddressList, scan_port);
                    } else {
                        scan_end = true;
                    }
                }
                if (!scan_end) {
                    for (int wc = 0; wc < 210; wc++) {
                        if (!tc.isEnabled())
                            break;
                        SystemClock.sleep(30);
                    }
                }
            }
            if (!tc.isEnabled()) {
                handler.post(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                });
            } else {
                handler.postDelayed(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                }, 10000);
            }
        }
    }).start();
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.view.TextModalInteractionView.java

@Override
public void doOnCreate(final Activity activity, Bundle onSavedInstanceState) {
    activity.setContentView(R.layout.apptentive_textmodal_interaction_center);

    TextView title = (TextView) activity.findViewById(R.id.title);
    if (interaction.getTitle() == null) {
        title.setVisibility(View.GONE);
    } else {/*from   w  w w.java 2  s  .  c  o  m*/
        title.setText(interaction.getTitle());
    }
    TextView body = (TextView) activity.findViewById(R.id.body);
    if (interaction.getBody() == null) {
        body.setVisibility(View.GONE);
    } else {
        body.setText(interaction.getBody());
    }

    LinearLayout bottomArea = (LinearLayout) activity.findViewById(R.id.bottom_area);
    List<Action> actions = interaction.getActions().getAsList();
    boolean vertical;
    if (actions != null && !actions.isEmpty()) {
        int totalChars = 0;
        for (Action button : actions) {
            totalChars += button.getLabel().length();
        }
        if (actions.size() == 1) {
            vertical = false;
        } else if (actions.size() == 2) {
            vertical = totalChars > MAX_TEXT_LENGTH_FOR_TWO_BUTTONS;
        } else if (actions.size() == 3) {
            vertical = totalChars > MAX_TEXT_LENGTH_FOR_THREE_BUTTONS;
        } else if (actions.size() == 4) {
            vertical = totalChars > MAX_TEXT_LENGTH_FOR_FOUR_BUTTONS;
        } else {
            vertical = true;
        }
        if (vertical) {
            bottomArea.setOrientation(LinearLayout.VERTICAL);
        } else {
            bottomArea.setOrientation(LinearLayout.HORIZONTAL);
        }

        for (int i = 0; i < actions.size(); i++) {
            final Action buttonAction = actions.get(i);
            final int position = i;
            ApptentiveDialogButton button = new ApptentiveDialogButton(activity);
            button.setText(buttonAction.getLabel());
            switch (buttonAction.getType()) {
            case dismiss:
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        JSONObject data = new JSONObject();
                        try {
                            data.put(TextModalInteraction.EVENT_KEY_ACTION_ID, buttonAction.getId());
                            data.put(Action.KEY_LABEL, buttonAction.getLabel());
                            data.put(TextModalInteraction.EVENT_KEY_ACTION_POSITION, position);
                        } catch (JSONException e) {
                            Log.e("Error creating Event data object.", e);
                        }
                        EngagementModule.engageInternal(activity, interaction,
                                TextModalInteraction.EVENT_NAME_DISMISS, data.toString());
                        activity.finish();
                    }
                });
                break;
            case interaction:
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        LaunchInteractionAction launchInteractionButton = (LaunchInteractionAction) buttonAction;
                        List<Invocation> invocations = launchInteractionButton.getInvocations();
                        String interactionIdToLaunch = null;
                        for (Invocation invocation : invocations) {
                            if (invocation.isCriteriaMet(activity)) {
                                interactionIdToLaunch = invocation.getInteractionId();
                                break;
                            }
                        }

                        Interaction invokedInteraction = null;
                        if (interactionIdToLaunch != null) {
                            Interactions interactions = InteractionManager.getInteractions(activity);
                            if (interactions != null) {
                                invokedInteraction = interactions.getInteraction(interactionIdToLaunch);
                            }
                        }

                        JSONObject data = new JSONObject();
                        try {
                            data.put(TextModalInteraction.EVENT_KEY_ACTION_ID, buttonAction.getId());
                            data.put(Action.KEY_LABEL, buttonAction.getLabel());
                            data.put(TextModalInteraction.EVENT_KEY_ACTION_POSITION, position);
                            data.put(TextModalInteraction.EVENT_KEY_INVOKED_INTERACTION_ID,
                                    invokedInteraction == null ? JSONObject.NULL : invokedInteraction.getId());
                        } catch (JSONException e) {
                            Log.e("Error creating Event data object.", e);
                        }

                        EngagementModule.engageInternal(activity, interaction,
                                TextModalInteraction.EVENT_NAME_INTERACTION, data.toString());
                        if (invokedInteraction != null) {
                            EngagementModule.launchInteraction(activity, invokedInteraction);
                        }

                        activity.finish();
                    }
                });
                break;
            }
            bottomArea.addView(button);
        }
    } else {
        bottomArea.setVisibility(View.GONE);
    }
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void clearPasteItemList() {
    LinearLayout lc = (LinearLayout) findViewById(R.id.explorer_filelist_copy_paste);
    isPasteEnabled = false;/*  w ww .j a  v a 2 s  .com*/
    pasteItemList = "";
    TextView pp = (TextView) findViewById(R.id.explorer_filelist_paste_list);
    //      TextView cc=(TextView)findViewById(R.id.explorer_filelist_paste_copycut);
    pp.setText(pasteItemList);
    lc.setVisibility(LinearLayout.GONE);
    setPasteButtonEnabled();
}

From source file:foam.opensauces.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {//from  w  w w .  j a v  a  2s. c  o m
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            v.setPadding(20, 20, 20, 20);
            v.setId(id);
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            /*                v.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View vv) {
                if (id!=99) {
                    ClipData dragData = ClipData.newPlainText("simple text", ""+id);
                    View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                    Log.i("starwisp","start drag id "+vv.getId());
                    v.startDrag(dragData, myShadow, null, 0);
                    v.setVisibility(View.GONE);
                    return true;
                }
                return false;
            }
                            });
            */
            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN && id != 99) {
                        //                            ClipData dragData = ClipData.newPlainText("simple text", ""+id);

                        ClipData dragData = new ClipData(
                                new ClipDescription(null, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                new ClipData.Item("" + id));

                        View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                        Log.i("starwisp", "start drag id " + vv.getId());
                        v.startDrag(dragData, myShadow, null, 0);
                        v.setVisibility(View.GONE);
                        return true;
                    }
                    return false;
                }
            });

            v.setOnDragListener(new View.OnDragListener() {
                public boolean onDrag(View vv, DragEvent event) {
                    final int action = event.getAction();
                    switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                            // returns true to indicate that the View can accept the dragged data.
                            return true;
                        } else {
                            // Returns false. During the current drag and drop operation, this View will
                            // not receive events again until ACTION_DRAG_ENDED is sent.
                            return false;
                        }
                    case DragEvent.ACTION_DRAG_ENTERED: {
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_LOCATION:
                        return true;
                    case DragEvent.ACTION_DRAG_EXITED: {
                        return true;
                    }
                    case DragEvent.ACTION_DROP: {
                        ClipData.Item item = event.getClipData().getItemAt(0);
                        String dragData = item.getText().toString();
                        Log.i("starwisp", "Dragged view is " + dragData);
                        int otherid = Integer.parseInt(dragData);
                        View otherw = ctx.findViewById(otherid);
                        Log.i("starwisp", "removing from parent " + ((View) otherw.getParent()).getId());

                        // check we are not adding to ourself
                        if (id != otherid) {
                            ((ViewManager) otherw.getParent()).removeView(otherw);
                            Log.i("starwisp", "adding to " + id);
                            v.addView(otherw);
                        }
                        otherw.setVisibility(View.VISIBLE);
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_ENDED: {
                        if (event.getResult()) {
                        } else {
                        }
                        ;
                        return true;
                    }
                    // An unknown action type was received.
                    default:
                        Log.e("starwisp", "Unknown action type received by OnDragListener.");
                        break;
                    }
                    ;
                    return true;
                }
            });
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setClickable(false);
            v.setEnabled(false);

            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    return false;
                }
            });

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);

            //              LinearLayout.LayoutParams lp =
            //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            //                v.setLayoutParams(lp);
            parent.addView(v);
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void closeScanRemoteNetworkProgressDlg(final Dialog dialog, final NotifyEvent p_ntfy,
        final ListView lv_ipaddr, final AdapterScanAddressResultList adap, final TextView tvmsg) {
    final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_scan_address);
    final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_progress);
    final Button btn_scan = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_ok);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_cancel);
    ll_addr.setVisibility(LinearLayout.VISIBLE);
    ll_prog.setVisibility(LinearLayout.GONE);
    btn_scan.setEnabled(true);/* w w w. java  2 s.  com*/
    btn_cancel.setEnabled(true);
    adap.setButtonEnabled(true);
    dialog.setOnKeyListener(null);
    dialog.setCancelable(true);
    if (p_ntfy != null)
        p_ntfy.notifyToListener(true, null);

}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void setPasteItemList() {
    LinearLayout lc = (LinearLayout) findViewById(R.id.explorer_filelist_copy_paste);
    TextView pp = (TextView) findViewById(R.id.explorer_filelist_paste_list);
    TextView cc = (TextView) findViewById(R.id.explorer_filelist_paste_copycut);
    if (isPasteEnabled) {
        String op = "Copy : ";
        if (!isPasteCopy)
            op = "Cut : ";
        cc.setText(op);//ww w.j ava  2 s  .  c om
        pp.setText(pasteItemList);
        lc.setVisibility(LinearLayout.VISIBLE);
    }
    setPasteButtonEnabled();
}

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()];
        }//  www  . j a  v a 2  s.  co  m

        @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.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void scanRemoteNetwork(final Dialog dialog, final ListView lv_ipaddr,
        final AdapterScanAddressResultList adap, final ArrayList<ScanAddressResultListItem> ipAddressList,
        final String subnet, final int begin_addr, final int end_addr, final NotifyEvent p_ntfy) {
    final Handler handler = new Handler();
    final ThreadCtrl tc = new ThreadCtrl();
    final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_scan_address);
    final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_progress);
    final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_remote_ntwk_progress_msg);
    final Button btn_scan = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_ok);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_btn_cancel);
    final Button scan_cancel = (Button) dialog.findViewById(R.id.scan_remote_ntwk_progress_cancel);

    final CheckBox cb_use_port_number = (CheckBox) dialog.findViewById(R.id.scan_remote_ntwk_use_port);
    final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_remote_ntwk_port_number);

    tvmsg.setText("");
    scan_cancel.setText(R.string.msgs_progress_spin_dlg_addr_cancel);
    ll_addr.setVisibility(LinearLayout.GONE);
    ll_prog.setVisibility(LinearLayout.VISIBLE);
    btn_scan.setEnabled(false);/*from   w w w  .  j  av  a 2  s  .com*/
    btn_cancel.setEnabled(false);
    adap.setButtonEnabled(false);
    scan_cancel.setEnabled(true);
    dialog.setOnKeyListener(new DialogBackKeyListener(mContext));
    dialog.setCancelable(false);
    // CANCEL?
    scan_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            scan_cancel.setText(mContext.getString(R.string.msgs_progress_dlg_canceling));
            scan_cancel.setEnabled(false);
            sendDebugLogMsg(1, "W", "IP Address list creation was cancelled");
            tc.setDisabled();
        }
    });
    dialog.show();

    sendDebugLogMsg(1, "I", "Scan IP address ransge is " + subnet + "." + begin_addr + " - " + end_addr);

    final String scan_prog = mContext.getString(R.string.msgs_ip_address_scan_progress);
    String p_txt = String.format(scan_prog, 0);
    tvmsg.setText(p_txt);

    new Thread(new Runnable() {
        @Override
        public void run() {//non UI thread
            mScanCompleteCount = 0;
            mScanAddrCount = end_addr - begin_addr + 1;
            int scan_thread = 50;
            String scan_port = "";
            if (cb_use_port_number.isChecked())
                scan_port = et_port_number.getText().toString();
            for (int i = begin_addr; i <= end_addr; i += scan_thread) {
                if (!tc.isEnabled())
                    break;
                boolean scan_end = false;
                for (int j = i; j < (i + scan_thread); j++) {
                    if (j <= end_addr) {
                        startRemoteNetworkScanThread(handler, tc, dialog, p_ntfy, lv_ipaddr, adap, tvmsg,
                                subnet + "." + j, ipAddressList, scan_port);
                    } else {
                        scan_end = true;
                    }
                }
                if (!scan_end) {
                    for (int wc = 0; wc < 210; wc++) {
                        if (!tc.isEnabled())
                            break;
                        SystemClock.sleep(30);
                    }
                }
            }
            if (!tc.isEnabled()) {
                handler.post(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                });
            } else {
                handler.postDelayed(new Runnable() {// UI thread
                    @Override
                    public void run() {
                        closeScanRemoteNetworkProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg);
                    }
                }, 10000);
            }
        }
    }).start();
}

From source file:com.mantz_it.rfanalyzer.MainActivity.java

/**
 * Will pop up a dialog to let the user adjust gain settings
 *//*w  w  w.j a  v a  2s  .c om*/
private void adjustGain() {
    if (source == null)
        return;

    int sourceType = Integer.valueOf(preferences.getString(getString(R.string.pref_sourceType), "1"));
    switch (sourceType) {
    case FILE_SOURCE:
        Toast.makeText(this, getString(R.string.filesource_doesnt_support_gain), Toast.LENGTH_LONG).show();
        break;
    case HACKRF_SOURCE:
        // Prepare layout:
        final LinearLayout view_hackrf = (LinearLayout) this.getLayoutInflater().inflate(R.layout.hackrf_gain,
                null);
        final SeekBar sb_hackrf_vga = (SeekBar) view_hackrf.findViewById(R.id.sb_hackrf_vga_gain);
        final SeekBar sb_hackrf_lna = (SeekBar) view_hackrf.findViewById(R.id.sb_hackrf_lna_gain);
        final TextView tv_hackrf_vga = (TextView) view_hackrf.findViewById(R.id.tv_hackrf_vga_gain);
        final TextView tv_hackrf_lna = (TextView) view_hackrf.findViewById(R.id.tv_hackrf_lna_gain);
        sb_hackrf_vga.setMax(HackrfSource.MAX_VGA_RX_GAIN / HackrfSource.VGA_RX_GAIN_STEP_SIZE);
        sb_hackrf_lna.setMax(HackrfSource.MAX_LNA_GAIN / HackrfSource.LNA_GAIN_STEP_SIZE);
        sb_hackrf_vga.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_hackrf_vga.setText("" + progress * HackrfSource.VGA_RX_GAIN_STEP_SIZE);
                ((HackrfSource) source).setVgaRxGain(progress * HackrfSource.VGA_RX_GAIN_STEP_SIZE);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        sb_hackrf_lna.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_hackrf_lna.setText("" + progress * HackrfSource.LNA_GAIN_STEP_SIZE);
                ((HackrfSource) source).setLnaGain(progress * HackrfSource.LNA_GAIN_STEP_SIZE);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        sb_hackrf_vga.setProgress(((HackrfSource) source).getVgaRxGain() / HackrfSource.VGA_RX_GAIN_STEP_SIZE);
        sb_hackrf_lna.setProgress(((HackrfSource) source).getLnaGain() / HackrfSource.LNA_GAIN_STEP_SIZE);

        // Show dialog:
        AlertDialog hackrfDialog = new AlertDialog.Builder(this).setTitle("Adjust Gain Settings")
                .setView(view_hackrf).setPositiveButton("Set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // safe preferences:
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putInt(getString(R.string.pref_hackrf_vgaRxGain),
                                sb_hackrf_vga.getProgress() * HackrfSource.VGA_RX_GAIN_STEP_SIZE);
                        edit.putInt(getString(R.string.pref_hackrf_lnaGain),
                                sb_hackrf_lna.getProgress() * HackrfSource.LNA_GAIN_STEP_SIZE);
                        edit.apply();
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // do nothing
                    }
                }).create();
        hackrfDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // sync source with (new/old) settings
                int vgaRxGain = preferences.getInt(getString(R.string.pref_hackrf_vgaRxGain),
                        HackrfSource.MAX_VGA_RX_GAIN / 2);
                int lnaGain = preferences.getInt(getString(R.string.pref_hackrf_lnaGain),
                        HackrfSource.MAX_LNA_GAIN / 2);
                if (((HackrfSource) source).getVgaRxGain() != vgaRxGain)
                    ((HackrfSource) source).setVgaRxGain(vgaRxGain);
                if (((HackrfSource) source).getLnaGain() != lnaGain)
                    ((HackrfSource) source).setLnaGain(lnaGain);
            }
        });
        hackrfDialog.show();
        hackrfDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        break;
    case RTLSDR_SOURCE:
        final int[] possibleGainValues = ((RtlsdrSource) source).getPossibleGainValues();
        final int[] possibleIFGainValues = ((RtlsdrSource) source).getPossibleIFGainValues();
        if (possibleGainValues.length <= 1 && possibleIFGainValues.length <= 1) {
            Toast.makeText(MainActivity.this, source.getName() + " does not support gain adjustment!",
                    Toast.LENGTH_LONG).show();
        }
        // Prepare layout:
        final LinearLayout view_rtlsdr = (LinearLayout) this.getLayoutInflater().inflate(R.layout.rtlsdr_gain,
                null);
        final LinearLayout ll_rtlsdr_gain = (LinearLayout) view_rtlsdr.findViewById(R.id.ll_rtlsdr_gain);
        final LinearLayout ll_rtlsdr_ifgain = (LinearLayout) view_rtlsdr.findViewById(R.id.ll_rtlsdr_ifgain);
        final Switch sw_rtlsdr_manual_gain = (Switch) view_rtlsdr.findViewById(R.id.sw_rtlsdr_manual_gain);
        final CheckBox cb_rtlsdr_agc = (CheckBox) view_rtlsdr.findViewById(R.id.cb_rtlsdr_agc);
        final SeekBar sb_rtlsdr_gain = (SeekBar) view_rtlsdr.findViewById(R.id.sb_rtlsdr_gain);
        final SeekBar sb_rtlsdr_ifGain = (SeekBar) view_rtlsdr.findViewById(R.id.sb_rtlsdr_ifgain);
        final TextView tv_rtlsdr_gain = (TextView) view_rtlsdr.findViewById(R.id.tv_rtlsdr_gain);
        final TextView tv_rtlsdr_ifGain = (TextView) view_rtlsdr.findViewById(R.id.tv_rtlsdr_ifgain);

        // Assign current gain:
        int gainIndex = 0;
        int ifGainIndex = 0;
        for (int i = 0; i < possibleGainValues.length; i++) {
            if (((RtlsdrSource) source).getGain() == possibleGainValues[i]) {
                gainIndex = i;
                break;
            }
        }
        for (int i = 0; i < possibleIFGainValues.length; i++) {
            if (((RtlsdrSource) source).getIFGain() == possibleIFGainValues[i]) {
                ifGainIndex = i;
                break;
            }
        }
        sb_rtlsdr_gain.setMax(possibleGainValues.length - 1);
        sb_rtlsdr_ifGain.setMax(possibleIFGainValues.length - 1);
        sb_rtlsdr_gain.setProgress(gainIndex);
        sb_rtlsdr_ifGain.setProgress(ifGainIndex);
        tv_rtlsdr_gain.setText("" + possibleGainValues[gainIndex]);
        tv_rtlsdr_ifGain.setText("" + possibleIFGainValues[ifGainIndex]);

        // Assign current manual gain and agc setting
        sw_rtlsdr_manual_gain.setChecked(((RtlsdrSource) source).isManualGain());
        cb_rtlsdr_agc.setChecked(((RtlsdrSource) source).isAutomaticGainControl());

        // Add listener to gui elements:
        sw_rtlsdr_manual_gain.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sb_rtlsdr_gain.setEnabled(isChecked);
                tv_rtlsdr_gain.setEnabled(isChecked);
                sb_rtlsdr_ifGain.setEnabled(isChecked);
                tv_rtlsdr_ifGain.setEnabled(isChecked);
                ((RtlsdrSource) source).setManualGain(isChecked);
                if (isChecked) {
                    ((RtlsdrSource) source).setGain(possibleGainValues[sb_rtlsdr_gain.getProgress()]);
                    ((RtlsdrSource) source).setIFGain(possibleIFGainValues[sb_rtlsdr_ifGain.getProgress()]);
                }
            }
        });
        cb_rtlsdr_agc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ((RtlsdrSource) source).setAutomaticGainControl(isChecked);
            }
        });
        sb_rtlsdr_gain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_rtlsdr_gain.setText("" + possibleGainValues[progress]);
                ((RtlsdrSource) source).setGain(possibleGainValues[progress]);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        sb_rtlsdr_ifGain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_rtlsdr_ifGain.setText("" + possibleIFGainValues[progress]);
                ((RtlsdrSource) source).setIFGain(possibleIFGainValues[progress]);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // Disable gui elements if gain cannot be adjusted:
        if (possibleGainValues.length <= 1)
            ll_rtlsdr_gain.setVisibility(View.GONE);
        if (possibleIFGainValues.length <= 1)
            ll_rtlsdr_ifgain.setVisibility(View.GONE);

        if (!sw_rtlsdr_manual_gain.isChecked()) {
            sb_rtlsdr_gain.setEnabled(false);
            tv_rtlsdr_gain.setEnabled(false);
            sb_rtlsdr_ifGain.setEnabled(false);
            tv_rtlsdr_ifGain.setEnabled(false);
        }

        // Show dialog:
        AlertDialog rtlsdrDialog = new AlertDialog.Builder(this).setTitle("Adjust Gain Settings")
                .setView(view_rtlsdr).setPositiveButton("Set", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // safe preferences:
                        SharedPreferences.Editor edit = preferences.edit();
                        edit.putBoolean(getString(R.string.pref_rtlsdr_manual_gain),
                                sw_rtlsdr_manual_gain.isChecked());
                        edit.putBoolean(getString(R.string.pref_rtlsdr_agc), cb_rtlsdr_agc.isChecked());
                        edit.putInt(getString(R.string.pref_rtlsdr_gain),
                                possibleGainValues[sb_rtlsdr_gain.getProgress()]);
                        edit.putInt(getString(R.string.pref_rtlsdr_ifGain),
                                possibleIFGainValues[sb_rtlsdr_ifGain.getProgress()]);
                        edit.apply();
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // do nothing
                    }
                }).create();
        rtlsdrDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                boolean manualGain = preferences.getBoolean(getString(R.string.pref_rtlsdr_manual_gain), false);
                boolean agc = preferences.getBoolean(getString(R.string.pref_rtlsdr_agc), false);
                int gain = preferences.getInt(getString(R.string.pref_rtlsdr_gain), 0);
                int ifGain = preferences.getInt(getString(R.string.pref_rtlsdr_ifGain), 0);
                ((RtlsdrSource) source).setGain(gain);
                ((RtlsdrSource) source).setIFGain(ifGain);
                ((RtlsdrSource) source).setManualGain(manualGain);
                ((RtlsdrSource) source).setAutomaticGainControl(agc);
                if (manualGain) {
                    // Note: This is a workaround. After setting manual gain to true we must
                    // rewrite the manual gain values:
                    ((RtlsdrSource) source).setGain(gain);
                    ((RtlsdrSource) source).setIFGain(ifGain);
                }
            }
        });
        rtlsdrDialog.show();
        rtlsdrDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        break;
    default:
        Log.e(LOGTAG, "adjustGain: Invalid source type: " + sourceType);
        break;
    }
}

From source file:net.clcworld.thermometer.TakeTemperatureReadingActivity.java

/** Called when the activity is first created. */
@Override//from   w ww  . j a  v a  2 s  . c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSelf = this;

    Intent i = new Intent();
    i.setClass(this, LauncherActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent relaunchIntent = PendingIntent.getActivity(this, 0, i, 0);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    Intent data = this.getIntent();

    if (data.getBooleanExtra("FROM_ALARM", false)) {
        // Only show the persistant notification if it's from the alarm.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_icon).setTicker(getString(R.string.notification))
                .setContentTitle(getString(R.string.app_name)).setContentText(getString(R.string.notification))
                .setOngoing(true).setOnlyAlertOnce(false).setContentIntent(relaunchIntent)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI).setLights(Color.RED, 500, 500);
        mNotificationManager.notify(NOTIFICATION_NUMBER, builder.build());
    }

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mFeeling = mPrefs.getString("lastFeeling", STATUS_WELL);
    mHistory = mPrefs.getString(PREFSKEY_HISTORY, "");
    final String id = mPrefs.getString("ID", "");

    setContentView(R.layout.temperature);
    mTemperatureEditText = (EditText) findViewById(R.id.temperature);
    mTemperatureEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

    final LinearLayout symptomsList = (LinearLayout) findViewById(R.id.symptoms);
    final CheckBox extremeTiredness = (CheckBox) findViewById(R.id.extremetiredness);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_EXTREMETIREDNESS, false)) {
        extremeTiredness.setChecked(true);
    }
    final CheckBox musclepain = (CheckBox) findViewById(R.id.musclepain);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_MUSCLEPAIN, false)) {
        musclepain.setChecked(true);
    }
    final CheckBox headache = (CheckBox) findViewById(R.id.headache);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_HEADACHE, false)) {
        headache.setChecked(true);
    }
    final CheckBox sorethroat = (CheckBox) findViewById(R.id.sorethroat);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_SORETHROAT, false)) {
        sorethroat.setChecked(true);
    }
    final CheckBox vomiting = (CheckBox) findViewById(R.id.vomiting);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_VOMITING, false)) {
        vomiting.setChecked(true);
    }
    final CheckBox diarrhea = (CheckBox) findViewById(R.id.diarrhea);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_DIARRHEA, false)) {
        diarrhea.setChecked(true);
    }
    final CheckBox rash = (CheckBox) findViewById(R.id.rash);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_RASH, false)) {
        rash.setChecked(true);
    }
    final CheckBox bleeding = (CheckBox) findViewById(R.id.bleeding);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_BLEEDING, false)) {
        bleeding.setChecked(true);
    }
    final CheckBox painrelief = (CheckBox) findViewById(R.id.painrelief);
    if (mPrefs.getBoolean(PREFSKEY_SYMPTOMS_PAINRELIEF, false)) {
        painrelief.setChecked(true);
    }

    final Button submitButton = (Button) findViewById(R.id.submit);
    submitButton.setText(R.string.save);
    final String destination = mPrefs.getString("DEST", "");
    if (destination.length() > 0) {
        submitButton.setText(getString(R.string.submit) + destination);
    }
    submitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            String tempString = mTemperatureEditText.getText().toString();
            try {
                float t = Float.parseFloat(tempString);
                // Come up with better thresholds + use an alert
                // confirmation prompt.
                if ((t < 91) || (t > 120)) {
                    Toast.makeText(mSelf, R.string.retake, Toast.LENGTH_LONG).show();
                    return;
                }

                mTemperatureEditText.setEnabled(false);
                submitButton.setEnabled(false);
                Editor editor = mPrefs.edit();
                editor.putLong("LAST_READING", System.currentTimeMillis());

                ArrayList<String> symptoms = new ArrayList<String>();
                if (mFeeling.equals(STATUS_WELL)) {
                    editor.putBoolean(PREFSKEY_SYMPTOMS_EXTREMETIREDNESS, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_MUSCLEPAIN, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_HEADACHE, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_SORETHROAT, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_VOMITING, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_DIARRHEA, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_RASH, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_BLEEDING, false);
                    editor.putBoolean(PREFSKEY_SYMPTOMS_PAINRELIEF, false);
                } else {
                    if (extremeTiredness.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_EXTREMETIREDNESS, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_EXTREMETIREDNESS);
                    }
                    if (musclepain.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_MUSCLEPAIN, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_MUSCLEPAIN);
                    }
                    if (headache.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_HEADACHE, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_HEADACHE);
                    }
                    if (sorethroat.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_SORETHROAT, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_SORETHROAT);
                    }
                    if (vomiting.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_VOMITING, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_VOMITING);
                    }
                    if (diarrhea.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_DIARRHEA, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_DIARRHEA);
                    }
                    if (rash.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_RASH, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_RASH);
                    }
                    if (bleeding.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_BLEEDING, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_BLEEDING);
                    }
                    if (painrelief.isChecked()) {
                        editor.putBoolean(PREFSKEY_SYMPTOMS_PAINRELIEF, true);
                        symptoms.add(PREFSKEY_SYMPTOMS_PAINRELIEF);
                    }
                }

                editor.commit();
                mNotificationManager.cancelAll();

                DecimalFormat decFormat = new DecimalFormat("0.0");
                sendData(id, decFormat.format(t), mFeeling, symptoms);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    mFeelingRadioGroup = (RadioGroup) findViewById(R.id.radioGroupFeeling);
    int selectedId = R.id.radioWell;
    if (mFeeling.equals(STATUS_SICK)) {
        selectedId = R.id.radioSick;
        if (destination.length() > 0) {
            symptomsList.setVisibility(View.VISIBLE);
        }
    }
    mFeelingRadioGroup.check(selectedId);
    mFeelingRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.radioSick) {
                mFeeling = STATUS_SICK;
                if (destination.length() > 0) {
                    symptomsList.setVisibility(View.VISIBLE);
                }
            } else {
                mFeeling = STATUS_WELL;
                symptomsList.setVisibility(View.GONE);
            }
            Editor editor = mPrefs.edit();
            editor.putString("lastFeeling", mFeeling);
            editor.commit();
        }
    });

    Button historyButton = (Button) findViewById(R.id.history);
    if (mHistory.length() < 1) {
        historyButton.setVisibility(View.GONE);
    }
    historyButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mSelf);
            alertDialogBuilder.setTitle(R.string.history);
            alertDialogBuilder.setPositiveButton(R.string.ok, null);
            AlertDialog dialog = alertDialogBuilder.create();
            TextView text = new TextView(mSelf);
            text.setTextSize(16);
            text.setPadding(40, 40, 40, 40);
            text.setText(mHistory);
            ScrollView scroll = new ScrollView(mSelf);
            scroll.addView(text);
            dialog.setView(scroll);
            dialog.show();
        }
    });

    Button viewTosButton = (Button) findViewById(R.id.viewtos);
    viewTosButton.setText(R.string.tos_title_local);
    mIsActivated = false;
    if (destination.length() > 0) {
        mIsActivated = true;
        viewTosButton.setText(R.string.tos_title_publichealth);
    }
    viewTosButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent viewTosIntent = new Intent();
            viewTosIntent.setClass(mSelf, TosActivity.class);
            viewTosIntent.putExtra("VIEW_ONLY", true);
            startActivity(viewTosIntent);
        }
    });
}