Example usage for android.widget Spinner setAdapter

List of usage examples for android.widget Spinner setAdapter

Introduction

In this page you can find the example usage for android.widget Spinner setAdapter.

Prototype

@Override
public void setAdapter(SpinnerAdapter adapter) 

Source Link

Document

Sets the SpinnerAdapter used to provide the data which backs this Spinner.

Usage

From source file:com.xperia64.timidityae.PlayerFragment.java

@SuppressLint("InflateParams")
public void showMidiDialog() {
    AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
    View v = getActivity().getLayoutInflater().inflate(R.layout.midi_options, null);
    Button speedUp = (Button) v.findViewById(R.id.speedUp);
    Button slowDown = (Button) v.findViewById(R.id.slowDown);
    Button keyUp = (Button) v.findViewById(R.id.keyUp);
    Button keyDown = (Button) v.findViewById(R.id.keyDown);
    Button vplus = (Button) v.findViewById(R.id.vplus);
    Button vminus = (Button) v.findViewById(R.id.vminus);
    Button export = (Button) v.findViewById(R.id.exportButton);
    Button saveCfg = (Button) v.findViewById(R.id.saveCfg);
    Button loadCfg = (Button) v.findViewById(R.id.loadCfg);
    Button savedefCfg = (Button) v.findViewById(R.id.savedefCfg);
    final Button deldefCfg = (Button) v.findViewById(R.id.deldefCfg);
    deldefCfg.setEnabled(new File(mActivity.currSongName + ".def.tcf").exists()
            || new File(mActivity.currSongName + ".def.tzf").exists());
    tempo = (TextView) v.findViewById(R.id.tempoText);
    pitch = (TextView) v.findViewById(R.id.pitchText);
    voices = (TextView) v.findViewById(R.id.voiceText);

    tempo.setText(String.format(getResources().getString(R.string.mop_tempo), JNIHandler.ttr,
            (int) (500000 / (double) JNIHandler.tt * 120 * (double) JNIHandler.ttr / 100 + 0.5)));
    pitch.setText(String.format(getResources().getString(R.string.mop_pitch),
            ((JNIHandler.koffset > 0) ? "+" : "") + Integer.toString(JNIHandler.koffset)));
    voices.setText(// w  ww . j a v  a  2 s .c  o  m
            String.format(getResources().getString(R.string.mop_voice), JNIHandler.voice, JNIHandler.maxvoice));
    speedUp.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(17, 1);
            JNIHandler.waitUntilReady();
            JNIHandler.tb++;
        }

    });
    slowDown.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(18, 1);
            JNIHandler.waitUntilReady();
            JNIHandler.tb--;
        }

    });
    keyUp.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(15, 1);
            JNIHandler.waitUntilReady();
        }

    });
    keyDown.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(16, -1);
            JNIHandler.waitUntilReady();
        }

    });
    vplus.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(19, 5);
            JNIHandler.waitUntilReady();
        }

    });
    vminus.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            JNIHandler.controlTimidity(20, 5);
            JNIHandler.waitUntilReady();
        }

    });
    export.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mActivity.dynExport();
        }

    });
    saveCfg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mActivity.saveCfg();
        }

    });
    loadCfg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mActivity.loadCfg();
        }

    });
    savedefCfg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            String value1;
            String value2;
            boolean alreadyExists = (new File(mActivity.currSongName + ".def.tcf").exists()
                    || new File(mActivity.currSongName + ".def.tzf").exists());
            boolean aWrite = true;
            String needRename1 = null;
            String needRename2 = null;
            String probablyTheRoot = "";
            String probablyTheDirectory = "";
            try {
                if (Globals.compressCfg)
                    new FileOutputStream(mActivity.currSongName + ".def.tzf", true).close();
                else
                    new FileOutputStream(mActivity.currSongName + ".def.tcf", true).close();
            } catch (FileNotFoundException e) {
                aWrite = false;
            } catch (IOException e) {
                e.printStackTrace();
            }
            final boolean canWrite = aWrite;
            if (!alreadyExists && canWrite) {
                new File(mActivity.currSongName + ".def.tcf").delete();
                new File(mActivity.currSongName + ".def.tzf").delete();
            }

            if (canWrite && new File(mActivity.currSongName).canWrite()) {
                value1 = mActivity.currSongName + (Globals.compressCfg ? ".def.tzf" : ".def.tcf");
                value2 = mActivity.currSongName + (Globals.compressCfg ? ".def.tcf" : ".def.tzf");
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
                //TODO
                // Write the file to getExternalFilesDir, then move it with the Uri
                // We need to tell JNIHandler that movement is needed.
                // This is pretty much done now?
                String[] tmp = Globals.getDocFilePaths(getActivity(), mActivity.currSongName);
                probablyTheDirectory = tmp[0];
                probablyTheRoot = tmp[1];
                if (probablyTheDirectory.length() > 1) {
                    needRename1 = (mActivity.currSongName).substring(
                            mActivity.currSongName.indexOf(probablyTheRoot) + probablyTheRoot.length())
                            + (Globals.compressCfg ? ".def.tzf" : ".def.tcf");
                    needRename2 = (mActivity.currSongName).substring(
                            mActivity.currSongName.indexOf(probablyTheRoot) + probablyTheRoot.length())
                            + (Globals.compressCfg ? ".def.tcf" : ".def.tzf");
                    value1 = probablyTheDirectory
                            + mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/'))
                            + (Globals.compressCfg ? ".def.tzf" : ".def.tcf");
                    value2 = probablyTheDirectory
                            + mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/'))
                            + (Globals.compressCfg ? ".def.tcf" : ".def.tzf");
                } else {
                    Toast.makeText(getActivity(),
                            "Could not write config file. Did you give Timidity write access to the root of your external sd card?",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Toast.makeText(getActivity(),
                            "Could not write config file. Did you give Timidity write access to the root of your external sd card?",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "Could not write config file. Permission denied.",
                            Toast.LENGTH_SHORT).show();
                }
                return;
            }
            final String finalval1 = value1;
            final String finalval2 = value2;
            final String needToRename1 = needRename1;
            final String needToRename2 = needRename2;
            final String probRoot = probablyTheRoot;
            if (alreadyExists) {
                AlertDialog dialog = new AlertDialog.Builder(mActivity).create();
                dialog.setTitle("Warning");
                dialog.setMessage("Overwrite default config file?");
                dialog.setCancelable(false);
                dialog.setButton(DialogInterface.BUTTON_POSITIVE,
                        getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {
                                if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    if (needToRename1 != null) {
                                        Globals.tryToDeleteFile(getActivity(), probRoot + needToRename1);
                                        Globals.tryToDeleteFile(getActivity(), finalval1);
                                        Globals.tryToDeleteFile(getActivity(), probRoot + needToRename2);
                                        Globals.tryToDeleteFile(getActivity(), finalval2);
                                    } else {
                                        Globals.tryToDeleteFile(getActivity(), finalval1);
                                        Globals.tryToDeleteFile(getActivity(), finalval2);
                                    }
                                } else {
                                    new File(mActivity.currSongName + ".def.tcf").delete();
                                    new File(mActivity.currSongName + ".def.tzf").delete();
                                }
                                mActivity.localfinished = false;
                                mActivity.saveCfgPart2(finalval1, needToRename1);
                                deldefCfg.setEnabled(true);
                                /*Intent new_intent = new Intent();
                                new_intent.setAction(getResources().getString(R.string.msrv_rec));
                                new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16);
                                new_intent.putExtra(getResources().getString(R.string.msrv_outfile), mActivity.currSongName+".def.tcf");
                                getActivity().sendBroadcast(new_intent);
                                deldefCfg.setEnabled(true);*/
                            }
                        });
                dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {

                            }
                        });
                dialog.show();

            } else {
                /*Intent new_intent = new Intent();
                 new_intent.setAction(getResources().getString(R.string.msrv_rec));
                 new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16);
                 new_intent.putExtra(getResources().getString(R.string.msrv_outfile), mActivity.currSongName+".def.tcf");
                 getActivity().sendBroadcast(new_intent);
                 deldefCfg.setEnabled(true);*/
                mActivity.localfinished = false;
                mActivity.saveCfgPart2(finalval1, needToRename1);
                deldefCfg.setEnabled(true);
            }
        }

    });

    deldefCfg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            if (new File(mActivity.currSongName + ".def.tcf").exists()
                    || new File(mActivity.currSongName + ".def.tzf").exists()) {
                boolean aWrite = true;
                try {
                    if (Globals.compressCfg)
                        new FileOutputStream(mActivity.currSongName + ".def.tzf", true).close();
                    else
                        new FileOutputStream(mActivity.currSongName + ".def.tcf", true).close();
                } catch (FileNotFoundException e) {
                    aWrite = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final boolean canWrite = aWrite;
                AlertDialog dialog = new AlertDialog.Builder(mActivity).create();
                dialog.setTitle("Warning");
                dialog.setMessage("Really delete default config file?");
                dialog.setCancelable(false);
                dialog.setButton(DialogInterface.BUTTON_POSITIVE,
                        getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {

                                if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    Globals.tryToDeleteFile(getActivity(), mActivity.currSongName + ".def.tzf");
                                    Globals.tryToDeleteFile(getActivity(), mActivity.currSongName + ".def.tcf");
                                } else {
                                    new File(mActivity.currSongName + ".def.tcf").delete();
                                    new File(mActivity.currSongName + ".def.tzf").delete();
                                }
                                deldefCfg.setEnabled(false);
                            }
                        });
                dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int buttonId) {

                            }
                        });
                dialog.show();

            }
        }

    });

    final Spinner x = (Spinner) v.findViewById(R.id.resampSpinner);
    List<String> arrayAdapter = new ArrayList<String>();
    for (String yyy : Globals.sampls)
        arrayAdapter.add(yyy);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, arrayAdapter);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    x.setAdapter(dataAdapter);
    firstSelection = true;
    x.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long id) {
            if (firstSelection)
                firstSelection = false;
            else {
                JNIHandler.setResampleTimidity(JNIHandler.currsamp = pos);
                JNIHandler.seekTo(JNIHandler.currTime);
            }
        }

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

        }

    });
    x.setSelection(JNIHandler.currsamp);
    if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        v.setBackgroundColor(Globals.theme == 1 ? Color.WHITE : Color.BLACK);

    b.setView(v);
    b.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    b.setTitle(getActivity().getResources().getString(R.string.mop));
    ddd = b.create();
    ddd.show();

}

From source file:dynamite.zafroshops.app.fragment.OpeningsDialogFragment.java

@NonNull
@Override//from www. j a va 2 s  .c  o m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    data = (ArrayList<MobileOpeningHourData>) getArguments().get(NEW_ZOP_OPENINGS);
    tempData = new ArrayList();

    for (int i = 0; i < data.size(); i++) {
        tempData.add(data.get(i).Copy());
    }

    // set spinners
    ArrayAdapter<String> openingsDayAdapter;
    ArrayAdapter<String> openingsHoursAdapter;
    ArrayAdapter<String> openingsMinutesAdapter;

    Activity activity = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final LayoutInflater inflater = activity.getLayoutInflater();
    View view = inflater.inflate(R.layout.openings_dialog, null);

    builder.setView(view).setTitle(R.string.openings_editing)
            .setPositiveButton(R.string.button_submit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    data.clear();
                    for (int i = 0; i < tempData.size(); i++) {
                        data.add(tempData.get(i).Copy());
                    }

                    Intent intent = new Intent();
                    intent.putExtra(NEW_ZOP_OPENINGS_COUNT_KEY, OpeningsDialogFragment.this.data.size());
                    getTargetFragment().onActivityResult(getTargetRequestCode(), NEW_ZOP_OPENINGS_RESULT_CODE,
                            intent);
                }
            }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

    final Spinner ohd = (Spinner) view.findViewById(R.id.openingsDay);
    final Spinner ohsh = (Spinner) view.findViewById(R.id.openingsStartHour);
    final Spinner ohsm = (Spinner) view.findViewById(R.id.openingsStartMinute);
    final Spinner oheh = (Spinner) view.findViewById(R.id.openingsEndHour);
    final Spinner ohem = (Spinner) view.findViewById(R.id.openingsEndMinute);

    if (days == null) {
        days = new ArrayList();
        for (int i = 0; i < 7; i++) {
            try {
                days.add(getString(R.string.class.getField("day" + i).getInt(null)));
            } catch (IllegalAccessException ignored) {
            } catch (NoSuchFieldException e) {
            }
        }
    }

    if (hours == null) {
        hours = new ArrayList();
        for (int i = 0; i < 24; i++) {
            hours.add(String.format("%02d", i));
        }
    }

    if (minutes == null) {
        minutes = new ArrayList();
        for (int i = 0; i < 4; i++) {
            minutes.add(String.format("%02d", i * 15));
        }
    }

    openingsDayAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, days);
    openingsDayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohd.setAdapter(openingsDayAdapter);

    openingsHoursAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, hours);
    openingsHoursAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohsh.setAdapter(openingsHoursAdapter);
    oheh.setAdapter(openingsHoursAdapter);

    openingsMinutesAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, minutes);
    openingsMinutesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ohsm.setAdapter(openingsMinutesAdapter);
    ohem.setAdapter(openingsMinutesAdapter);

    // set current openings
    openingHoursContainer = (LinearLayout) view.findViewById(R.id.openingHours);
    openingHoursLabel = (TextView) view.findViewById(R.id.openingHoursLabel);
    openingHoursDeleteButton = (Button) view.findViewById(R.id.openingsHoursDelete);

    ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);

    // set buttons
    view.findViewById(R.id.openingsHoursAdd).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // get data
            final int position = ohd.getSelectedItemPosition();
            MobileOpeningHourData item = null;
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }

            // update data
            if (item == null) {
                item = new MobileOpeningHourData((byte) position);
                tempData.add(item);
            }

            final MobileOpeningHour moh = new MobileOpeningHour();
            moh.StartTimeHour = (byte) ohsh.getSelectedItemPosition();
            moh.StartTimeMinute = (byte) (ohsm.getSelectedItemPosition() * 15);
            moh.EndTimeHour = (byte) oheh.getSelectedItemPosition();
            moh.EndTimeMinute = (byte) (ohem.getSelectedItemPosition() * 15);

            MobileOpeningHour temp = null;
            try {
                temp = Iterables.find(item.Hours, new Predicate<MobileOpeningHour>() {
                    @Override
                    public boolean apply(MobileOpeningHour input) {
                        return input.compareTo(moh) == 0;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }

            if (temp == null) {
                item.Hours.add(moh);
            }

            // sort data
            Collections.sort(item.Hours);
            Collections.sort(tempData);

            // update view
            ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);
            openingHoursDeleteButton.setEnabled(true);
        }
    });
    openingHoursDeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // get data
            final int position = ohd.getSelectedItemPosition();
            MobileOpeningHourData item = null;
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }
            // update data
            if (item != null) {
                tempData.remove(item);
                openingHoursDeleteButton.setEnabled(false);
            }
            // update view
            ZopItemFragment.setOpeningsList(tempData, openingHoursContainer, inflater, openingHoursLabel);
        }
    });
    ohd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
            MobileOpeningHourData item = null;
            // get data
            try {
                item = Iterables.find(tempData, new Predicate<MobileOpeningHourData>() {
                    @Override
                    public boolean apply(MobileOpeningHourData input) {
                        return input.Day == position;
                    }
                });
            } catch (NoSuchElementException ignored) {
            }
            // update view
            if (item != null) {
                openingHoursDeleteButton.setEnabled(true);
            } else {
                openingHoursDeleteButton.setEnabled(false);
            }
        }

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

        }
    });

    return builder.create();
}

From source file:com.money.manager.ex.common.CategoryListFragment.java

/**
 * Show alter binaryDialog, for create or edit new category
 *//*from   w  ww.ja va2  s .c  o m*/
private void showDialogEditSubCategoryName(final SQLTypeTransaction type, final int categoryId,
        final int subCategoryId, final CharSequence subCategName) {

    // inflate view
    View viewDialog = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_new_edit_subcategory, null);

    final EditText edtSubCategName = (EditText) viewDialog.findViewById(R.id.editTextCategName);
    final Spinner spnCategory = (Spinner) viewDialog.findViewById(R.id.spinnerCategory);
    // set category description
    edtSubCategName.setText(subCategName);
    if (!TextUtils.isEmpty(subCategName)) {
        edtSubCategName.setSelection(subCategName.length());
    }

    // Fill categories list.
    CategoryService categoryService = new CategoryService(getActivity());
    final List<Category> categories = categoryService.getList();

    ArrayList<String> categoryNames = new ArrayList<>();
    ArrayList<Integer> categoryIds = new ArrayList<>();
    for (Category category : categories) {
        categoryIds.add(category.getId());
        categoryNames.add(category.getName().toString());
    }
    ArrayAdapter<String> adapterCategory = new ArrayAdapter<>(getActivity(),
            android.R.layout.simple_spinner_item, categoryNames);
    adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnCategory.setAdapter(adapterCategory);
    //select category if present
    if (categoryId > 0) {
        spnCategory.setSelection(categoryIds.indexOf(categoryId), true);
    }

    int titleId = type.equals(SQLTypeTransaction.INSERT) ? R.string.add_subcategory
            : R.string.edit_categoryName;

    new MaterialDialog.Builder(getContext()).customView(viewDialog, true)
            .icon(FontIconDrawable.inflate(getContext(), R.xml.ic_tag)).title(titleId)
            .positiveText(android.R.string.ok).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    // get category description
                    String name = edtSubCategName.getText().toString();
                    // check position
                    if (spnCategory.getSelectedItemPosition() == Spinner.INVALID_POSITION)
                        return;
                    // get category id
                    int categId = categories.get(spnCategory.getSelectedItemPosition()).getId();
                    ContentValues values = new ContentValues();
                    values.put(Subcategory.CATEGID, categId);
                    values.put(Subcategory.SUBCATEGNAME, name);

                    SubcategoryRepository repo = new SubcategoryRepository(getActivity());

                    // check type transaction is request
                    switch (type) {
                    case INSERT:
                        if (getActivity().getContentResolver().insert(repo.getUri(), values) == null) {
                            Toast.makeText(getActivity(), R.string.db_insert_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case UPDATE:
                        if (getActivity().getContentResolver().update(repo.getUri(), values, Subcategory.CATEGID
                                + "=" + categoryId + " AND " + Subcategory.SUBCATEGID + "=" + subCategoryId,
                                null) == 0) {
                            Toast.makeText(getActivity(), R.string.db_update_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    // restart loader
                    restartLoader();
                }
            }).negativeText(android.R.string.cancel).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    dialog.cancel();
                }
            }).build().show();
}

From source file:de.mkrtchyan.recoverytools.RecoveryTools.java

public void optimizeLayout() throws NullPointerException {

    try {/*from   www. j a v  a 2s .co  m*/
        if (mDevice.isRecoverySupported() || mDevice.isKernelSupported()) {
            /** If device is supported start setting up layout */
            if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
                /** Setting layout for flashing over external App for example File Browser */
                setContentView(R.layout.flash_as);
                RelativeLayout FlashAsLayout = (RelativeLayout) findViewById(R.layout.flash_as);
                String path;
                if ((path = getIntent().getData().getPath()) != null) {
                    final File IMG = new File(path);
                    if (IMG.exists()) {
                        TextView tvFlashAs = (TextView) findViewById(R.id.tvFlashAs);
                        tvFlashAs.setText(String.format(getString(R.string.flash_as), IMG.getName()));
                    } else {
                        exit();
                    }
                    RadioButton optAsRecovery = (RadioButton) findViewById(R.id.optAsRecovery);
                    RadioButton optAsKernel = (RadioButton) findViewById(R.id.optAsKernel);

                    if (!mDevice.isRecoverySupported()) {
                        FlashAsLayout.removeView(optAsRecovery);
                        optAsKernel.setChecked(true);
                    }
                    if (!mDevice.isKernelSupported()) {
                        FlashAsLayout.removeView((optAsKernel));
                    }
                } else {
                    exit();
                }
            } else {
                setContentView(R.layout.recovery_tools);

                mRecoveryToolsLayout = (DrawerLayout) findViewById(R.id.RecoveryToolsLayout);
                mSwipeUpdater = (SwipeRefreshLayout) findViewById(R.id.swipe_updater);
                mSwipeUpdater.setColorScheme(R.color.custom_green, android.R.color.black, R.color.custom_green,
                        android.R.color.darker_gray);
                mSwipeUpdater.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        Downloader updater = new Downloader(mContext, "http://dslnexus.de/Android/", "img_sums",
                                RecoveryCollectionFile, new Runnable() {
                                    @Override
                                    public void run() {
                                        mDevice = new Device(mContext);
                                    }
                                });
                        updater.setOverrideFile(true);
                        updater.setRetry(true);
                        updater.setHidden(true);
                        Toast.makeText(mContext, "Refreshing recovery list", Toast.LENGTH_SHORT).show();
                        updater.setAfterDownload(new Runnable() {
                            @Override
                            public void run() {
                                mSwipeUpdater.setRefreshing(false);
                                Toast.makeText(mContext, "Update finished", Toast.LENGTH_SHORT).show();
                                mDevice.loadRecoveryList();
                            }
                        });
                        updater.execute();
                    }
                });
                LayoutInflater layoutInflater = getLayoutInflater();

                DrawerLayout mMenuDrawer = (DrawerLayout) layoutInflater.inflate(R.layout.menu_drawer,
                        mRecoveryToolsLayout, true);
                DrawerLayout mBackupDrawer = (DrawerLayout) layoutInflater.inflate(R.layout.backup_drawer,
                        mRecoveryToolsLayout, true);
                mRecoveryToolsLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
                ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(mActivity, mRecoveryToolsLayout,
                        R.drawable.ic_drawer, R.string.settings, R.string.app_name);
                mRecoveryToolsLayout.setDrawerListener(mDrawerToggle);
                mDrawerToggle.syncState();
                mDrawerToggle.setDrawerIndicatorEnabled(true);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setHomeButtonEnabled(true);

                String Styles[] = getResources().getStringArray(R.array.styles);
                if (mMenuDrawer != null) {
                    Spinner spStyle = (Spinner) mMenuDrawer.findViewById(R.id.spStyle);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity,
                            R.layout.custom_list_item, Styles);
                    adapter.setDropDownViewResource(R.layout.custom_list_item);

                    spStyle.setAdapter(adapter);
                    spStyle.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            switch (position) {
                            case 1:
                                Common.setIntegerPref(mContext, PREF_NAME, PREF_STYLE,
                                        APPCOMPAT_LIGHT_DARK_BAR);
                                restartActivity();
                                break;
                            case 2:
                                Common.setIntegerPref(mContext, PREF_NAME, PREF_STYLE, APPCOMPAT_LIGHT);
                                restartActivity();
                                break;
                            case 3:
                                Common.setIntegerPref(mContext, PREF_NAME, PREF_STYLE, APPCOMPAT_DARK);
                                restartActivity();
                                break;
                            }
                        }

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

                        }
                    });
                    CheckBox cbShowAds = (CheckBox) mMenuDrawer.findViewById(R.id.cbShowAds);
                    CheckBox cbLog = (CheckBox) mMenuDrawer.findViewById(R.id.cbLog);

                    cbShowAds.setChecked(Common.getBooleanPref(mContext, PREF_NAME, PREF_KEY_ADS));
                    cbLog.setChecked(Common.getBooleanPref(mContext, Shell.PREF_NAME, Shell.PREF_LOG));
                    if (cbLog.isChecked()) {
                        findViewById(R.id.bShowLogs).setVisibility(View.VISIBLE);
                    } else {
                        findViewById(R.id.bShowLogs).setVisibility(View.INVISIBLE);
                    }
                    cbShowAds.setChecked(Common.getBooleanPref(mContext, PREF_NAME, PREF_KEY_ADS));

                }

                final TextView RecoveryVersion = (TextView) findViewById(R.id.tvVersion);
                RecoveryVersion.setText(mDevice.getRecoveryVersion() + "\n" + mDevice.getKernelVersion());
                loadBackupDrawer();

                AdView adView = (AdView) findViewById(R.id.adView);
                ViewGroup MainParent = (ViewGroup) adView.getParent();
                /** Removing ads if user has turned off */
                if (!Common.getBooleanPref(mContext, PREF_NAME, PREF_KEY_ADS)) {
                    if (adView != null && MainParent != null) {
                        MainParent.removeView(adView);
                    }
                }

                if (MainParent != null) {
                    if (!mDevice.isKernelSupported()) {
                        /** If Kernel flashing is not supported remove flash options */
                        MainParent.removeView(findViewById(R.id.bFlashKernel));
                    }
                    if (!mDevice.isRecoverySupported()) {
                        /** If Recovery flashing is not supported remove flash options */
                        MainParent.removeView(findViewById(R.id.bFlashRecovery));
                    }
                }

                if (mBackupDrawer != null) {
                    ViewGroup BackupDrawerParent = (ViewGroup) mBackupDrawer.getParent();
                    if (mDevice.isRecoveryOverRecovery()) {
                        BackupDrawerParent.removeView(mBackupDrawer);
                    } else {
                        View createKernelBackup = findViewById(R.id.bCreateKernelBackup);
                        View kernelBackups = findViewById(R.id.lvKernelBackups);
                        View createRecoveryBackup = findViewById(R.id.bCreateRecoveryBackup);
                        View recoveryBackups = findViewById(R.id.lvRecoveryBackups);
                        if (!mDevice.isKernelSupported()) {
                            /** If Kernel flashing is not supported remove backup views */
                            ((ViewGroup) createKernelBackup.getParent()).removeView(createKernelBackup);
                            ((ViewGroup) kernelBackups.getParent()).removeView(kernelBackups);
                        }
                        if (!mDevice.isRecoverySupported()) {
                            /** If Recovery flashing is not supported remove backup views */
                            ((ViewGroup) createRecoveryBackup.getParent()).removeView(createRecoveryBackup);
                            ((ViewGroup) recoveryBackups.getParent()).removeView(recoveryBackups);
                        }
                    }
                }
            }
        }

    } catch (NullPointerException e) {
        throw new NullPointerException("Error while setting up Layout " + e.getMessage());
    }
}

From source file:com.cmput301w15t15.travelclaimsapp.activitys.EditClaimActivity.java

/**
 * Function that is called when you press the add tag
 * /*from   ww  w  .  j  a  va  2 s.  c  o  m*/
 * Creates a alert dialog that gives the user the option 
 * of adding a previously added tag or entering a new tag name
 * 
 * @param view
 */
public void addTagButton(View view) {
    final EditText enterTag = new EditText(this);
    final Spinner tagSpinner = new Spinner(this);
    //Linear layout that holds enterTag and tagSpinner views
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    tagSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View arg1, int position, long id) {
            enterTag.setText(parent.getItemAtPosition(position).toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub      
        }
    });

    enterTag.setHint("Enter tag");
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    //get all the tags currently added to claims in application claimlist
    ArrayList<Tag> tags = ClaimListController.getTagList();
    String t[] = new String[tags.size()];
    for (int i = 0; i < tags.size(); i++) {
        t[i] = tags.get(i).getName();
    }
    //create a arrayadaptor for displaying the tagSpinner view, and set it
    ArrayAdapter<String> tagA = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, t);
    tagSpinner.setAdapter(tagA);
    //add views to linear layout and set the Linear layout view as the alert dialog view 
    ll.addView(tagSpinner);
    ll.addView(enterTag);
    alert.setView(ll);

    alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            Tag tag = new Tag(enterTag.getText().toString());
            if (theClaim.getTagList().getTag(enterTag.getText().toString()) != null) {
                return;
            }
            ClaimListController.addTag(theClaim, tag);
            tagAdaptor.notifyDataSetChanged();
        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });

    alert.show();
}

From source file:com.xperia64.timidityae.TrackFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    reset();//from   w  w  w . ja v a 2s. c om

    fileList = new ArrayAdapter<String>(getActivity(), R.layout.row);
    for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) {
        fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form),
                (getActivity().getResources()
                        .getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)),
                (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i)));
    }
    channelList.setAdapter(fileList);
    channelList.setOnItemClickListener(new OnItemClickListener() {

        @SuppressLint("InflateParams")
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            View v = getActivity().getLayoutInflater().inflate(R.layout.track_dialog, null);
            final Spinner instSpin = (Spinner) v.findViewById(R.id.instSpin);
            instSpin.setClickable(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2));
            instSpin.setOnLongClickListener(null);
            instSpin.setEnabled(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2));
            List<String> arrayAdapter = new ArrayList<String>();
            final int offset = (!JNIHandler.drums.get(arg2)) ? 0 : 34;
            if (!JNIHandler.drums.get(arg2)) {
                for (String inst : getActivity().getResources().getStringArray(R.array.midi_instruments))
                    arrayAdapter.add(inst);
            } else {
                for (String inst : getActivity().getResources().getStringArray(R.array.midi_drums))
                    arrayAdapter.add(inst);
            }
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_spinner_item, arrayAdapter);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            } else {
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            }

            dataAdapter.setNotifyOnChange(false);
            if (!JNIHandler.drums.get(arg2)) {
                instSpin.setAdapter(dataAdapter);
                instSpin.setSelection(localInst.get(arg2) - offset);
            }
            final EditText txtVol = (EditText) v.findViewById(R.id.txtVol);
            txtVol.setText(Integer.toString(localVol.get(arg2)));
            txtVol.setClickable(JNIHandler.custVol.get(arg2));
            txtVol.setEnabled(JNIHandler.custVol.get(arg2));

            final SeekBar volSeek = (SeekBar) v.findViewById(R.id.volSeek);
            volSeek.setClickable(JNIHandler.custVol.get(arg2));
            volSeek.setEnabled(JNIHandler.custVol.get(arg2));
            volSeek.setMax(127);
            volSeek.setProgress(localVol.get(arg2));
            volSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                    if (arg2 && !fromUser) {
                        fromUser = true;
                        txtVol.setText(Integer.toString(arg0.getProgress()));
                    } else {
                        fromUser = false;
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar arg0) {
                }

            });

            txtVol.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    if (!fromUser) {
                        if (s.length() > 0) {
                            int numm = Integer.parseInt(s.toString());
                            if (numm > 127) {
                                fromUser = true;
                                numm = 127;
                            }
                            if (numm < 0) {
                                fromUser = true;
                                numm = 0;
                            }
                            if (fromUser) {
                                txtVol.setText(Integer.toString(numm));
                            }
                            fromUser = true;
                            volSeek.setProgress(numm);
                            fromUser = false;
                        }
                    } else {
                        fromUser = false;
                    }
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            final CheckBox inst = (CheckBox) v.findViewById(R.id.defInstr);
            inst.setEnabled(!JNIHandler.drums.get(arg2));
            inst.setChecked(!JNIHandler.custInst.get(arg2));
            inst.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                    instSpin.setClickable(!arg1);
                    instSpin.setEnabled(!arg1);
                }

            });
            final CheckBox vol = (CheckBox) v.findViewById(R.id.defVol);
            vol.setChecked(!JNIHandler.custVol.get(arg2));
            //System.out.println("Def inst: "+(!JNIHandler.custInst.get(arg2)?"true":"false")+" def vol: "+(!JNIHandler.custVol.get(arg2)?"true":"false"));
            vol.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                    volSeek.setClickable(!arg1);
                    volSeek.setEnabled(!arg1);
                    txtVol.setClickable(!arg1);
                    txtVol.setEnabled(!arg1);
                }

            });
            if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                v.setBackgroundColor(Globals.theme == 1 ? Color.WHITE : Color.BLACK);
            b.setView(v);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    JNIHandler.custInst.set(arg2, !inst.isChecked());
                    JNIHandler.custVol.set(arg2, !vol.isChecked());
                    JNIHandler.setChannelVolumeTimidity(arg2 | (JNIHandler.custVol.get(arg2) ? 0x800 : 0x8000),
                            volSeek.getProgress());
                    JNIHandler.setChannelTimidity(arg2 | (JNIHandler.custInst.get(arg2) ? 0x800 : 0x8000),
                            instSpin.getSelectedItemPosition());
                    if (!JNIHandler.paused && Globals.isPlaying == 0)
                        JNIHandler.seekTo(JNIHandler.currTime);
                    //bigCounter=12;
                    updateList();
                }
            });

            b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            b.setTitle(String.format((getActivity().getResources().getString(R.string.trk_form2)), (arg2 + 1)));
            ddd = b.create();
            ddd.show();
        }

    });
}

From source file:no.barentswatch.fiskinfo.BaseActivity.java

/**
 * This function creates a dialog which allows the user to register a item
 * or tool used./*from   w ww  .j  a va 2  s .c  om*/
 * 
 * @param activityContext
 *            The context of the current activity.
 */
public void registerItemAndToolUsed(Context activityContext) {
    LayoutInflater layoutInflater = getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.dialog_register_tool, (null));
    final AlertDialog builder = new AlertDialog.Builder(activityContext).create();
    builder.setTitle(R.string.register_tool_dialog_title);
    builder.setView(view);
    final EditText startingCoordinates = (EditText) view.findViewById(R.id.registerStartingCoordinatesOfTool);
    final EditText endCoordinates = (EditText) view.findViewById(R.id.registerEndCoordinatesOfTool);
    final TextView invalidInputFeedback = (TextView) view.findViewById(R.id.RegisterToolInvalidInputTextView);

    if (lastSetStartingPosition != null) {
        startingCoordinates.setText(lastSetStartingPosition);
    }
    if (lastSetEndPosition != null) {
        endCoordinates.setText(lastSetEndPosition);
    }

    final Spinner projectionSpinner = (Spinner) view.findViewById(R.id.projectionChangingSpinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.projections,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    projectionSpinner.setPrompt("Velg projeksjon");
    projectionSpinner.setAdapter(
            new NoDefaultSpinner(adapter, R.layout.spinner_layout_select_projection, activityContext));

    final Spinner itemSpinner = (Spinner) view.findViewById(R.id.registerMiscType);
    ArrayAdapter<CharSequence> itemAdapter = ArrayAdapter.createFromResource(this, R.array.tool_types,
            android.R.layout.simple_spinner_item);
    itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    itemSpinner.setPrompt("Velg redskapstype");
    itemSpinner.setAdapter(
            new NoDefaultSpinner(itemAdapter, R.layout.spinner_layout_choose_tool, activityContext));

    Button fetchToolStartingCoordinatesButton = (Button) view
            .findViewById(R.id.dialogFetchUserStartingCoordinates);
    Button fetchToolEndCoordinatesButton = (Button) view.findViewById(R.id.dialogFetchUserEndCoordinates);

    fetchToolStartingCoordinatesButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setToolCoordinatesPosition(startingCoordinates);
        }
    });

    fetchToolEndCoordinatesButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setToolCoordinatesPosition(endCoordinates);
        }
    });

    acceptButtonRegister(view, builder, startingCoordinates, endCoordinates, invalidInputFeedback,
            projectionSpinner, itemSpinner);

    Button cancelButton = (Button) view.findViewById(R.id.DialogCancelRegistration);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            builder.dismiss();
        }
    });

    builder.show();
}

From source file:reportsas.com.formulapp.Formulario.java

public LinearLayout obtenerLayout(LayoutInflater infla, Pregunta preg) {
    int id;/*from w w  w. ja va 2 s  .  c om*/
    int tipo_pregunta = preg.getTipoPregunta();
    LinearLayout pregunta;
    TextView textView;
    TextView textAyuda;
    switch (tipo_pregunta) {
    case 1:
        id = R.layout.pregunta_texto;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloPregunta);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        break;
    case 2:
        id = R.layout.pregunta_multitexto;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.mtxtTritulo);
        textAyuda = (TextView) pregunta.findViewById(R.id.mtxtAyuda);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    case 3:
        id = R.layout.pregunta_seleccion;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloSeleccion);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_seleccion);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        RadioGroup rg = (RadioGroup) pregunta.findViewById(R.id.opcionesUnica);
        ArrayList<OpcionForm> opciones = preg.getOpciones();
        final ArrayList<RadioButton> rb = new ArrayList<RadioButton>();

        for (int i = 0; i < opciones.size(); i++) {
            OpcionForm opcion = opciones.get(i);
            rb.add(new RadioButton(this));
            rg.addView(rb.get(i));
            rb.get(i).setText(opcion.getEtInicial());

        }
        final TextView respt = (TextView) pregunta.findViewById(R.id.respuestaGruop);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonID = group.getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton) group.findViewById(radioButtonID);
                respt.setText(radioButton.getText());
            }
        });

        break;
    case 4:
        id = R.layout.pregunta_multiple;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloMultiple);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_mltiple);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        ArrayList<OpcionForm> opciones2 = preg.getOpciones();
        final EditText ediOtros = new EditText(this);
        ArrayList<CheckBox> cb = new ArrayList<CheckBox>();

        for (int i = 0; i < opciones2.size(); i++) {
            OpcionForm opcion = opciones2.get(i);
            cb.add(new CheckBox(this));
            pregunta.addView(cb.get(i));
            cb.get(i).setText(opcion.getEtInicial());
            if (opcion.getEditble().equals("S")) {

                ediOtros.setEnabled(false);
                ediOtros.setId(R.id.edtTexto);
                pregunta.addView(ediOtros);
                cb.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            ediOtros.setEnabled(true);
                        } else {
                            ediOtros.setText("");
                            ediOtros.setEnabled(false);
                        }
                    }
                });
            }

        }
        TextView spacio = new TextView(this);
        spacio.setText("        ");
        spacio.setVisibility(View.INVISIBLE);
        pregunta.addView(spacio);
        break;
    case 5:
        id = R.layout.pregunta_escala;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloEscala);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_escala);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());

        TextView etInicial = (TextView) pregunta.findViewById(R.id.etInicial);
        TextView etFinal = (TextView) pregunta.findViewById(R.id.etFinal);
        OpcionForm opci = preg.getOpciones().get(0);
        etInicial.setText(opci.getEtInicial());
        etFinal.setText(opci.getEtFinal());
        final TextView respEscala = (TextView) pregunta.findViewById(R.id.seleEscala);
        RatingBar rtBar = (RatingBar) pregunta.findViewById(R.id.escala);
        rtBar.setNumStars(Integer.parseInt(opci.getValores().get(0).getDescripcion()));
        rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                respEscala.setText("" + Math.round(rating));
            }
        });

        break;
    case 6:
        id = R.layout.pregunta_lista;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloLista);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_lista);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        ArrayList<OpcionForm> opciones3 = preg.getOpciones();
        //Creamos la lista
        LinkedList<ObjetoSpinner> opcn = new LinkedList<ObjetoSpinner>();
        //La poblamos con los ejemplos
        for (int i = 0; i < opciones3.size(); i++) {
            opcn.add(new ObjetoSpinner(opciones3.get(i).getIdOpcion(), opciones3.get(i).getEtInicial()));
        }

        //Creamos el adaptador*/
        Spinner listad = (Spinner) pregunta.findViewById(R.id.opcionesListado);
        ArrayAdapter<ObjetoSpinner> spinner_adapter = new ArrayAdapter<ObjetoSpinner>(this,
                android.R.layout.simple_spinner_item, opcn);
        //Aadimos el layout para el men y se lo damos al spinner
        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        listad.setAdapter(spinner_adapter);

        break;
    case 7:
        id = R.layout.pregunta_tabla;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloTabla);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_tabla);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        TableLayout tba = (TableLayout) pregunta.findViewById(R.id.tablaOpciones);
        ArrayList<OpcionForm> opciones4 = preg.getOpciones();
        ArrayList<RadioButton> radiosbotonoes = new ArrayList<RadioButton>();
        for (int i = 0; i < opciones4.size(); i++) {
            TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.row_pregunta_tabla, null);
            RadioGroup tg_valores = (RadioGroup) row.findViewById(R.id.valoresRow);

            final ArrayList<RadioButton> valoOpc = new ArrayList<RadioButton>();
            ArrayList<Valor> valoresT = opciones4.get(i).getValores();
            for (int k = 0; k < valoresT.size(); k++) {
                RadioButton rb_nuevo = new RadioButton(this);
                rb_nuevo.setText(valoresT.get(k).getDescripcion());
                tg_valores.addView(rb_nuevo);
                valoOpc.add(rb_nuevo);
            }

            ((TextView) row.findViewById(R.id.textoRow)).setText(opciones4.get(i).getEtInicial());
            tba.addView(row);
        }
        TextView espacio = new TextView(this);
        espacio.setText("        ");
        pregunta.addView(espacio);
        break;
    case 8:
        id = R.layout.pregunta_fecha;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloFecha);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_fecha);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    case 9:
        id = R.layout.pregunta_hora;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloHora);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_hora);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    default:
        id = R.layout.pregunta_multiple;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloMultiple);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_mltiple);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        break;
    }

    return pregunta;
}

From source file:com.example.yudiandrean.socioblood.FeedActivity.java

@SuppressLint("NewApi")
@Override//www  .  j  ava2  s .  c o m
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final Dialog d = new Dialog(context);
    setContentView(R.layout.feed_activity);
    postrequest = (TextView) findViewById(R.id.editText);

    WindowManager manager = (WindowManager) getSystemService(Activity.WINDOW_SERVICE);
    final int width, height;
    ActionBar.LayoutParams params;

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
        width = manager.getDefaultDisplay().getWidth();
        height = manager.getDefaultDisplay().getHeight();
    } else {
        Point point = new Point();
        manager.getDefaultDisplay().getSize(point);
        width = point.x;
        height = point.y;
    }

    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (!session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(FeedActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    listView = (ListView) findViewById(R.id.list);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    swipeRefreshLayout.setOnRefreshListener(this);

    // add button listener
    postrequest.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            try {
                d.requestWindowFeature(Window.FEATURE_NO_TITLE);
                d.setContentView(R.layout.post_request);
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                lp.copyFrom(d.getWindow().getAttributes());
                lp.width = width;
                lp.height = height;
                d.getWindow().setAttributes(lp);
            } catch (AndroidRuntimeException e) {
            } catch (Exception e) {
            }

            final Spinner rhesusspinner = (Spinner) d.findViewById(R.id.rhesus_spinner);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(FeedActivity.this,
                    android.R.layout.simple_spinner_dropdown_item) {

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View v = super.getView(position, convertView, parent);
                    if (position == getCount()) {
                        ((TextView) v.findViewById(android.R.id.text1)).setText("");
                        ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
                    }

                    return v;
                }

                @Override
                public int getCount() {
                    return super.getCount() - 1; // you dont display last item. It is used as hint.
                }

            };

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter.add("+");
            adapter.add("-");
            adapter.add("Rhesus");

            rhesusspinner.setAdapter(adapter);
            rhesusspinner.setSelection(adapter.getCount()); //display hint

            final Spinner bloodspinner = (Spinner) d.findViewById(R.id.bloodtype_spinner);
            ArrayAdapter<String> bloodadapter = new ArrayAdapter<String>(FeedActivity.this,
                    android.R.layout.simple_spinner_dropdown_item) {

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View v = super.getView(position, convertView, parent);
                    if (position == getCount()) {
                        ((TextView) v.findViewById(android.R.id.text1)).setText("");
                        ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
                    }

                    return v;
                }

                @Override
                public int getCount() {
                    return super.getCount() - 1; // you dont display last item. It is used as hint.
                }

            };

            bloodadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            bloodadapter.add("O");
            bloodadapter.add("A");
            bloodadapter.add("B");
            bloodadapter.add("AB");
            bloodadapter.add("Desired Type");

            bloodspinner.setAdapter(bloodadapter);
            bloodspinner.setSelection(bloodadapter.getCount()); //display hint

            //Buttons-Editexts
            Button btnpost = (Button) d.findViewById(R.id.post);
            final EditText userInput = (EditText) d.findViewById(R.id.editTextDialogUserInput);

            d.show();

            btnpost.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (bloodspinner.getSelectedItem().toString().equals("Desired Type")) {
                        Toast.makeText(getApplicationContext(), "Input Blood Type!", Toast.LENGTH_SHORT).show();
                    } else if (rhesusspinner.getSelectedItem().toString().equals("Rhesus")) {
                        Toast.makeText(getApplicationContext(), "Input Rhesus!", Toast.LENGTH_SHORT).show();
                    } else if (userInput.getText().toString().equals("")) {
                        Toast.makeText(getApplicationContext(), "Input your request message!",
                                Toast.LENGTH_SHORT).show();
                    } else {

                        int uid = session.currentUID();

                        String message = userInput.getText().toString();
                        String post_bloodtype = bloodspinner.getSelectedItem().toString();
                        String post_rhesus = rhesusspinner.getSelectedItem().toString();

                        NetAsync(d, view, uid, message, post_bloodtype, post_rhesus);

                    }
                }
            });

        }
    });

    //        // We first check for cached request
    //        Cache cache = FeedController.getInstance().getRequestQueue().getCache();
    //        Entry entry = cache.get(URL_FEED);
    //        if (entry != null) {
    //            // fetch the data from cache
    //            try {
    //                String data = new String(entry.data, "UTF-8");
    //                try {
    //                    parseJsonFeed(new JSONObject(data));
    //                } catch (JSONException e) {
    //                    e.printStackTrace();
    //                }
    //            } catch (UnsupportedEncodingException e) {
    //                e.printStackTrace();
    //            }
    //
    //        } else {
    // making fresh volley request and getting json

    /**
     * Showing Swipe Refresh animation on activity create
     * As animation won't start on onCreate, post runnable is used
     */
    swipeRefreshLayout.post(new Runnable() {
        @Override
        public void run() {
            swipeRefreshLayout.setRefreshing(true);
            getTimelineAsync();
        }
    });

}

From source file:com.stanleyidesis.quotograph.ui.activity.LWQSettingsActivity.java

void setupSettings() {
    final String[] refreshPreferenceOptions = getResources().getStringArray(R.array.refresh_preference_options);
    ArrayAdapter<String> refreshOptionsAdapter = new ArrayAdapter<>(this, R.layout.spinner_item,
            refreshPreferenceOptions);/*  w  w w . j av a 2  s  .c  o  m*/
    refreshOptionsAdapter.setDropDownViewResource(R.layout.spinner_drop_down_item);
    Spinner refreshSpinner = findById(settingsContainer, R.id.spinner_lwq_settings_refresh);
    refreshSpinner.setAdapter(refreshOptionsAdapter);
    refreshSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
            // Log refresh rate choice
            LWQLoggerHelper.get().logRefreshRate((String) adapterView.getAdapter().getItem(index));
            final int[] refreshValues = getResources().getIntArray(R.array.refresh_preference_values);
            LWQPreferences.setRefreshPreference(refreshValues[index]);
            LWQAlarmController.resetAlarm();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    updateRefreshSpinner();

    // Blur
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        findById(settingsContainer, R.id.sb_lwq_settings_blur).setVisibility(View.GONE);
    } else {
        SeekBar blurBar = findById(settingsContainer, R.id.sb_lwq_settings_blur);
        blurBar.setProgress(LWQPreferences.getBlurPreference());
        blurBar.setOnSeekBarChangeListener(this);
    }

    // Dim
    SeekBar dimBar = findById(settingsContainer, R.id.sb_lwq_settings_dim);
    dimBar.setProgress(LWQPreferences.getDimPreference());
    dimBar.setOnSeekBarChangeListener(this);

    AppCompatCheckBox doubleTapCheckbox = findById(this, R.id.check_lwq_settings_double_tap);
    doubleTapCheckbox.setChecked(LWQPreferences.isDoubleTapEnabled());

    // Fonts
    findById(settingsContainer, R.id.btn_lwq_settings_fonts).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseFontsDialog = new MaterialDialog.Builder(LWQSettingsActivity.this).title("Choose Fonts")
                    .adapter(new FontMultiselectAdapter(LWQSettingsActivity.this), LWQSettingsActivity.this)
                    .alwaysCallMultiChoiceCallback().autoDismiss(false).canceledOnTouchOutside(true)
                    .cancelListener(LWQSettingsActivity.this).build();
            chooseFontsDialog.show();
            // Log view
            AnalyticsUtils.trackScreenView(AnalyticsUtils.SCREEN_FONTS);
        }
    });

    // Images
    findById(settingsContainer, R.id.btn_lwq_settings_images).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeState(stateChooseImageSources);
            // Log view
            AnalyticsUtils.trackScreenView(AnalyticsUtils.SCREEN_IMAGES);
        }
    });
}