android.widget.TableRow

Here are the examples of the java api android.widget.TableRow taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

103 Examples 7

19 Source : ColorPickerPalette.java
with GNU Affero General Public License v3.0
from threema-ch

/**
 * Adds swatches to table in a serpentine format.
 */
public void drawPalette(int[] colors, int selectedColor, String[] colorContentDescriptions) {
    if (colors == null) {
        return;
    }
    this.removeAllViews();
    int tableElements = 0;
    int rowElements = 0;
    int rowNumber = 0;
    // Fills the table with swatches based on the array of colors.
    TableRow row = createTableRow();
    for (int color : colors) {
        View colorSwatch = createColorSwatch(color, selectedColor);
        setSwatchDescription(rowNumber, tableElements, rowElements, color == selectedColor, colorSwatch, colorContentDescriptions);
        addSwatchToRow(row, colorSwatch, rowNumber);
        tableElements++;
        rowElements++;
        if (rowElements == mNumColumns) {
            addView(row);
            row = createTableRow();
            rowElements = 0;
            rowNumber++;
        }
    }
    // Create blank views to fill the row if the last row has not been filled.
    if (rowElements > 0) {
        while (rowElements != mNumColumns) {
            addSwatchToRow(row, createBlankSpace(), rowNumber);
            rowElements++;
        }
        addView(row);
    }
}

19 Source : ColorPickerPalette.java
with GNU Affero General Public License v3.0
from threema-ch

private TableRow createTableRow() {
    TableRow row = new TableRow(getContext());
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(params);
    return row;
}

19 Source : TableBuilder.java
with Apache License 2.0
from iqiyi

public void saveData(View view, String[] data) {
    TableRow row = (TableRow) getTableRow(view);
    saveData(row, data);
}

19 Source : TableBuilder.java
with Apache License 2.0
from iqiyi

// save data after edit: mData cant be null
public void saveData(TableRow row, String[] data) {
    if (data == null || data.length == 0)
        return;
    int id = layout.indexOfChild(row);
    if (colNames != null && colNames.length > 0) {
        id--;
    }
    int start = id * colCount;
    int end = start + colCount;
    int dataEnd = mData == null ? 0 : mData.length;
    if (end > dataEnd)
        return;
    if (mData != null) {
        int count = Math.min(colCount, data.length);
        int p = 0;
        end = start + count;
        for (int i = start; i < end; i++) {
            mData[i] = data[p++];
        }
    }
}

19 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

private void updateView() {
    int count = configTable.getChildCount() - 2;
    for (int i = 0; i < count; i++) {
        TableRow row = ((TableRow) configTable.getChildAt(i + 1));
        setVisibility(row);
    }
}

19 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

private void newItem(TableRow row) {
    addEmptyEndItem();
}

19 Source : MultiLineRadioGroup.java
with MIT License
from Gavras

// adds and returns a table row
private TableRow addTableRow() {
    TableRow tableRow = getTableRow();
    mTableLayout.addView(tableRow);
    return tableRow;
}

19 Source : ExifHolder.java
with Apache License 2.0
from boybeak

/**
 * Created by gaoyunfei on 2017/9/6.
 */
public clreplaced ExifHolder extends AbsViewHolder<ExifDelegate> {

    private TableRow makeRow, modelRow, etRow, apertureRow, flRow, isoRow;

    private AppCompatTextView makeTv, modelTv, etTv, apertureTv, flTv, isoTv;

    public ExifHolder(View itemView) {
        super(itemView);
        makeRow = findViewById(R.id.exif_make);
        modelRow = findViewById(R.id.exif_model);
        etRow = findViewById(R.id.exif_exposure_time);
        apertureRow = findViewById(R.id.exif_aperture);
        flRow = findViewById(R.id.exif_focal_length);
        isoRow = findViewById(R.id.exif_iso);
        makeTv = findViewById(R.id.exif_make_value);
        modelTv = findViewById(R.id.exif_model_value);
        etTv = findViewById(R.id.exif_exposure_time_value);
        apertureTv = findViewById(R.id.exif_aperture_value);
        flTv = findViewById(R.id.exif_focal_length_value);
        isoTv = findViewById(R.id.exif_iso_value);
    }

    @Override
    public void onBindView(Context context, ExifDelegate t, int position, DelegateAdapter adapter) {
        Exif exif = t.getSource();
        makeRow.setVisibility(visibility(exif.make));
        modelRow.setVisibility(visibility(exif.model));
        etRow.setVisibility(visibility(exif.exposure_time));
        apertureRow.setVisibility(visibility(exif.aperture));
        flRow.setVisibility(visibility(exif.focal_length));
        isoRow.setVisibility(exif.iso == 0 ? View.GONE : View.VISIBLE);
        makeTv.setText(exif.make);
        modelTv.setText(exif.model);
        etTv.setText(exif.exposure_time);
        apertureTv.setText(exif.aperture);
        flTv.setText(exif.focal_length);
        isoTv.setText(exif.iso + "");
    }

    private int visibility(String value) {
        return TextUtils.isEmpty(value) ? View.GONE : View.VISIBLE;
    }
}

18 Source : ColorPickerPalette.java
with GNU Affero General Public License v3.0
from threema-ch

/**
 * Appends a swatch to the end of the row for even-numbered rows (starting with row 0),
 * to the beginning of a row for odd-numbered rows.
 */
private static void addSwatchToRow(TableRow row, View swatch, int rowNumber) {
    if (rowNumber % 2 == 0) {
        row.addView(swatch);
    } else {
        row.addView(swatch, 0);
    }
}

18 Source : TableRowSubject.java
with Apache License 2.0
from pkware

/**
 * Propositions for {@link TableRow} subjects.
 */
public clreplaced TableRowSubject extends AbstractLinearLayoutSubject<TableRow> {

    @Nullable
    private final TableRow actual;

    public TableRowSubject(@Nonnull FailureMetadata failureMetadata, @Nullable TableRow actual) {
        super(failureMetadata, actual);
        this.actual = actual;
    }

    public void hasVirtualChildCount(int count) {
        check("getVirtualChildCount()").that(actual.getVirtualChildCount()).isEqualTo(count);
    }
}

18 Source : ImuFragment.java
with GNU General Public License v3.0
from peng-zhihui

public clreplaced ImuFragment extends SherlockFragment {

    private Button mButton;

    public TextView mPitchView;

    public TextView mRollView;

    public TextView mCoefficient;

    private TableRow mTableRow;

    private Handler mHandler = new Handler();

    private Runnable mRunnable;

    private int counter = 0;

    boolean buttonState;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.imu, container, false);
        mPitchView = (TextView) v.findViewById(R.id.textView1);
        mRollView = (TextView) v.findViewById(R.id.textView2);
        mCoefficient = (TextView) v.findViewById(R.id.textView3);
        mTableRow = (TableRow) v.findViewById(R.id.tableRowCoefficient);
        mButton = (Button) v.findViewById(R.id.button);
        mHandler.postDelayed(new Runnable() {

            // Hide the menu icon and tablerow if there is no build in gyroscope in the device
            @Override
            public void run() {
                if (SensorFusion.IMUOutputSelection == -1)
                    // Run this again if it hasn't initialized the sensors yet
                    mHandler.postDelayed(this, 100);
                else if (// Check if a gyro is supported
                SensorFusion.IMUOutputSelection != 2)
                    // If not then hide the tablerow
                    mTableRow.setVisibility(View.GONE);
            }
        }, // Wait 100ms before running the code
        100);
        MainActivity.buttonState = false;
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        mRunnable = new Runnable() {

            @Override
            public void run() {
                // Update IMU data every 50ms
                mHandler.postDelayed(this, 50);
                if (MainActivity.mSensorFusion == null)
                    return;
                mPitchView.setText(MainActivity.mSensorFusion.pitch);
                mRollView.setText(MainActivity.mSensorFusion.roll);
                mCoefficient.setText(MainActivity.mSensorFusion.coefficient);
                counter++;
                if (counter > 2) {
                    // Only send data every 150ms time
                    counter = 0;
                    if (MainActivity.mChatService == null)
                        return;
                    if (MainActivity.mChatService.getState() == BluetoothChatService.STATE_CONNECTED && MainActivity.currentTabSelected == ViewPagerAdapter.IMU_FRAGMENT) {
                        buttonState = mButton.isPressed();
                        MainActivity.buttonState = buttonState;
                        if (// Check if joystick is released or we are not in landscape mode
                        MainActivity.joystickReleased || getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
                            // Set the ViewPager according to the button
                            CustomViewPager.setPagingEnabled(!buttonState);
                        else
                            CustomViewPager.setPagingEnabled(false);
                        if (MainActivity.joystickReleased) {
                            if (buttonState) {
                                lockRotation();
                                MainActivity.mChatService.write(MainActivity.sendIMUValues + MainActivity.mSensorFusion.pitch + ',' + MainActivity.mSensorFusion.roll + ";");
                                mButton.setText(R.string.sendingData);
                            } else {
                                unlockRotation();
                                MainActivity.mChatService.write(MainActivity.sendStop);
                                mButton.setText(R.string.notSendingData);
                            }
                        }
                    } else {
                        mButton.setText(R.string.button);
                        if (MainActivity.currentTabSelected == ViewPagerAdapter.IMU_FRAGMENT && MainActivity.joystickReleased)
                            CustomViewPager.setPagingEnabled(true);
                    }
                }
            }
        };
        // Update IMU data every 50ms
        mHandler.postDelayed(mRunnable, 50);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void lockRotation() {
        if (getResources().getBoolean(R.bool.isTablet)) {
            // Check if the layout can rotate
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
                // Lock screen orientation so it doesn't rotate
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
            else {
                // Lock rotation manually - source: http://blogs.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
                int rotation = MainActivity.getRotation();
                int lock;
                if (// Landscape
                rotation == Surface.ROTATION_90)
                    lock = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                else if (// Reverse Portrait
                rotation == Surface.ROTATION_180)
                    lock = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                else if (// Reverse Landscape
                rotation == Surface.ROTATION_270)
                    lock = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                else
                    lock = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                getActivity().setRequestedOrientation(lock);
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void unlockRotation() {
        if (getResources().getBoolean(R.bool.isTablet)) {
            // Check if the layout can rotate
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
                // Unlock screen orientation
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
            else
                // Unlock screen orientation
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(mRunnable);
        unlockRotation();
    }
}

18 Source : InfoAlbero.java
with GNU General Public License v3.0
from michelesalvador

public clreplaced InfoAlbero extends AppCompatActivity {

    Gedcom gc;

    @Override
    protected void onCreate(Bundle bandolo) {
        super.onCreate(bandolo);
        setContentView(R.layout.info_albero);
        LinearLayout scatola = findViewById(R.id.info_scatola);
        final int idAlbero = getIntent().getIntExtra("idAlbero", 1);
        final Armadio.Creplacedetto questoAlbero = Globale.preferenze.getAlbero(idAlbero);
        final File file = new File(getFilesDir(), idAlbero + ".json");
        String i;
        if (!file.exists()) {
            i = getText(R.string.item_exists_but_file) + "\n" + file.getAbsolutePath();
        } else {
            i = getText(R.string.file) + ": " + file.getAbsolutePath();
            gc = Alberi.apriGedcomTemporaneo(idAlbero, false);
            if (gc == null)
                i += "\n\n" + getString(R.string.no_useful_data);
            else {
                // Aggiornamento dei dati automatico o su richiesta
                if (questoAlbero.individui < 100) {
                    aggiornaDati(gc, questoAlbero);
                } else {
                    Button bottoneAggiorna = findViewById(R.id.info_aggiorna);
                    bottoneAggiorna.setVisibility(View.VISIBLE);
                    bottoneAggiorna.setOnClickListener(v -> {
                        aggiornaDati(gc, questoAlbero);
                        recreate();
                    });
                }
                i += "\n\n" + getText(R.string.persons) + ": " + questoAlbero.individui + "\n" + getText(R.string.families) + ": " + gc.getFamilies().size() + "\n" + getText(R.string.generations) + ": " + questoAlbero.generazioni + "\n" + getText(R.string.media) + ": " + questoAlbero.media + "\n" + getText(R.string.sources) + ": " + gc.getSources().size() + "\n" + getText(R.string.repositories) + ": " + gc.getRepositories().size();
                if (questoAlbero.radice != null) {
                    i += "\n" + getText(R.string.root) + ": " + U.epiteto(gc.getPerson(questoAlbero.radice));
                }
                if (questoAlbero.condivisioni != null && !questoAlbero.condivisioni.isEmpty()) {
                    i += "\n\n" + getText(R.string.shares) + ":";
                    for (Armadio.Invio invio : questoAlbero.condivisioni) {
                        i += "\n" + dataIdVersoData(invio.data);
                        if (gc.getSubmitter(invio.submitter) != null)
                            i += " - " + nomeAutore(gc.getSubmitter(invio.submitter));
                    }
                }
            }
        }
        ((TextView) findViewById(R.id.info_statistiche)).setText(i);
        Button bottoneHeader = scatola.findViewById(R.id.info_gestisci_testata);
        if (gc != null) {
            Header h = gc.getHeader();
            if (h == null) {
                bottoneHeader.setText(R.string.create_header);
                bottoneHeader.setOnClickListener(view -> {
                    gc.setHeader(AlberoNuovo.creaTestata(file.getName()));
                    U.salvaJson(gc, idAlbero);
                    recreate();
                });
            } else {
                scatola.findViewById(R.id.info_testata).setVisibility(View.VISIBLE);
                if (h.getFile() != null)
                    poni(getText(R.string.file), h.getFile());
                if (h.getCharacterSet() != null) {
                    poni(getText(R.string.characrter_set), h.getCharacterSet().getValue());
                    poni(getText(R.string.version), h.getCharacterSet().getVersion());
                }
                // uno spazietto
                spazio();
                poni(getText(R.string.language), h.getLanguage());
                spazio();
                poni(getText(R.string.copyright), h.getCopyright());
                spazio();
                if (h.getGenerator() != null) {
                    poni(getText(R.string.software), h.getGenerator().getName() != null ? h.getGenerator().getName() : h.getGenerator().getValue());
                    poni(getText(R.string.version), h.getGenerator().getVersion());
                    if (h.getGenerator().getGeneratorCorporation() != null) {
                        poni(getText(R.string.corporation), h.getGenerator().getGeneratorCorporation().getValue());
                        if (h.getGenerator().getGeneratorCorporation().getAddress() != null)
                            // non è male
                            poni(getText(R.string.address), h.getGenerator().getGeneratorCorporation().getAddress().getDisplayValue());
                        poni(getText(R.string.telephone), h.getGenerator().getGeneratorCorporation().getPhone());
                        poni(getText(R.string.fax), h.getGenerator().getGeneratorCorporation().getFax());
                    }
                    spazio();
                    if (h.getGenerator().getGeneratorData() != null) {
                        poni(getText(R.string.source), h.getGenerator().getGeneratorData().getValue());
                        poni(getText(R.string.date), h.getGenerator().getGeneratorData().getDate());
                        poni(getText(R.string.copyright), h.getGenerator().getGeneratorData().getCopyright());
                    }
                }
                spazio();
                if (h.getSubmitter(gc) != null)
                    // todo: renderlo cliccabile?
                    poni(getText(R.string.submitter), nomeAutore(h.getSubmitter(gc)));
                if (gc.getSubmission() != null)
                    // todo: cliccabile
                    poni(getText(R.string.submission), gc.getSubmission().getDescription());
                spazio();
                if (h.getGedcomVersion() != null) {
                    poni(getText(R.string.gedcom), h.getGedcomVersion().getVersion());
                    poni(getText(R.string.form), h.getGedcomVersion().getForm());
                }
                poni(getText(R.string.destination), h.getDestination());
                spazio();
                if (h.getDateTime() != null) {
                    poni(getText(R.string.date), h.getDateTime().getValue());
                    poni(getText(R.string.time), h.getDateTime().getTime());
                }
                spazio();
                for (Estensione est : U.trovaEstensioni(h)) {
                    // ogni estensione nella sua riga
                    poni(est.nome, est.testo);
                }
                spazio();
                if (righetta != null)
                    ((TableLayout) findViewById(R.id.info_tabella)).removeView(righetta);
                // Bottone per aggiorna l'header GEDCOM coi parametri di Family Gem
                bottoneHeader.setOnClickListener(view -> {
                    h.setFile(idAlbero + ".json");
                    CharacterSet caratteri = h.getCharacterSet();
                    if (caratteri == null) {
                        caratteri = new CharacterSet();
                        h.setCharacterSet(caratteri);
                    }
                    caratteri.setValue("UTF-8");
                    caratteri.setVersion(null);
                    Locale loc = new Locale(Locale.getDefault().getLanguage());
                    h.setLanguage(loc.getDisplayLanguage(Locale.ENGLISH));
                    Generator programma = h.getGenerator();
                    if (programma == null) {
                        programma = new Generator();
                        h.setGenerator(programma);
                    }
                    programma.setValue("FAMILY_GEM");
                    programma.setName(getString(R.string.app_name));
                    // programma.setVersion( BuildConfig.VERSION_NAME ); // lo farà salvaJson()
                    programma.setGeneratorCorporation(null);
                    GedcomVersion versioneGc = h.getGedcomVersion();
                    if (versioneGc == null) {
                        versioneGc = new GedcomVersion();
                        h.setGedcomVersion(versioneGc);
                    }
                    versioneGc.setVersion("5.5.1");
                    versioneGc.setForm("LINEAGE-LINKED");
                    h.setDestination(null);
                    U.salvaJson(gc, idAlbero);
                    recreate();
                });
                U.mettiNote(scatola, h, true);
            }
            // Estensioni del Gedcom, ovvero tag non standard di livello 0 zero
            for (Estensione est : U.trovaEstensioni(gc)) {
                U.metti(scatola, est.nome, est.testo);
            }
        } else
            bottoneHeader.setVisibility(View.GONE);
    }

    String dataIdVersoData(String id) {
        if (id == null)
            return "";
        return id.substring(0, 4) + "-" + id.substring(4, 6) + "-" + id.substring(6, 8) + " " + id.substring(8, 10) + ":" + id.substring(10, 12) + ":" + id.substring(12);
    }

    static String nomeAutore(Submitter autor) {
        String nome = autor.getName();
        if (nome == null)
            nome = "[" + Globale.contesto.getString(R.string.no_name) + "]";
        else if (nome.isEmpty())
            nome = "[" + Globale.contesto.getString(R.string.empty_name) + "]";
        return nome;
    }

    static void aggiornaDati(Gedcom gc, Armadio.Creplacedetto albero) {
        albero.individui = gc.getPeople().size();
        albero.generazioni = quanteGenerazioni(gc, albero.radice != null ? albero.radice : U.trovaRadice(gc));
        ListaMedia visitaMedia = new ListaMedia(gc, 0);
        gc.accept(visitaMedia);
        albero.media = visitaMedia.lista.size();
        Globale.preferenze.salva();
    }

    // impedisce di mettere più di uno spazio() consecutivo
    boolean testoMesso;

    void poni(CharSequence replacedolo, String testo) {
        if (testo != null) {
            TableRow riga = new TableRow(getApplicationContext());
            TextView cella1 = new TextView(getApplicationContext());
            cella1.setTextColor(Color.BLACK);
            cella1.setTypeface(null, Typeface.BOLD);
            cella1.setPadding(0, 0, 10, 0);
            cella1.setGravity(Gravity.END);
            cella1.setText(replacedolo);
            riga.addView(cella1);
            TextView cella2 = new TextView(getApplicationContext());
            cella2.setTextColor(0xFF000000);
            cella2.setPadding(0, 0, 0, 0);
            cella2.setText(testo);
            riga.addView(cella2);
            ((TableLayout) findViewById(R.id.info_tabella)).addView(riga);
            testoMesso = true;
        }
    }

    TableRow righetta;

    void spazio() {
        if (testoMesso) {
            righetta = new TableRow(getApplicationContext());
            View cella = new View(getApplicationContext());
            cella.setBackgroundResource(R.color.primario);
            righetta.addView(cella);
            TableRow.LayoutParams param = (TableRow.LayoutParams) cella.getLayoutParams();
            param.weight = 1;
            param.span = 2;
            param.height = 1;
            param.topMargin = 5;
            param.bottomMargin = 5;
            cella.setLayoutParams(param);
            ((TableLayout) findViewById(R.id.info_tabella)).addView(righetta);
            testoMesso = false;
        }
    }

    public static int quanteGenerazioni(Gedcom gc, String radice) {
        if (gc.getPeople().isEmpty())
            return 0;
        genMin = 0;
        genMax = 0;
        risaliGenerazioni(gc.getPerson(radice), gc, 0);
        // Rimuove dalle persone l'estensione 'gen' per permettere successivi conteggi
        for (Person p : gc.getPeople()) {
            p.getExtensions().remove("gen");
            if (p.getExtensions().isEmpty())
                p.setExtensions(null);
        }
        return 1 - genMin + genMax;
    }

    static int genMin;

    static int genMax;

    // riceve una Person e trova il numero della generazione di antenati più remota
    static void risaliGenerazioni(Person p, Gedcom gc, int gen) {
        if (gen < genMin)
            genMin = gen;
        // aggiunge l'estensione per indicare che è preplacedato da questa Persona
        p.putExtension("gen", gen);
        // se è un capostipite va a contare le generazioni di discendenti
        if (p.getParentFamilies(gc).isEmpty())
            discendiGenerazioni(p, gc, gen);
        for (Family f : p.getParentFamilies(gc)) {
            // intercetta eventuali fratelli del capostipite
            if (f.getHusbands(gc).isEmpty() && f.getWives(gc).isEmpty()) {
                for (Person frate : f.getChildren(gc)) if (frate.getExtension("gen") == null)
                    discendiGenerazioni(frate, gc, gen);
            }
            for (Person padre : f.getHusbands(gc)) if (padre.getExtension("gen") == null)
                risaliGenerazioni(padre, gc, gen - 1);
            for (Person madre : f.getWives(gc)) if (madre.getExtension("gen") == null)
                risaliGenerazioni(madre, gc, gen - 1);
        }
    }

    // riceve una Person e trova il numero della generazione più remota di discendenti
    static void discendiGenerazioni(Person p, Gedcom gc, int gen) {
        if (gen > genMax)
            genMax = gen;
        p.putExtension("gen", gen);
        for (Family fam : p.getSpouseFamilies(gc)) {
            // individua anche la famiglia dei coniugi
            for (Person moglie : fam.getWives(gc)) if (moglie.getExtension("gen") == null)
                risaliGenerazioni(moglie, gc, gen);
            for (Person marito : fam.getHusbands(gc)) if (marito.getExtension("gen") == null)
                risaliGenerazioni(marito, gc, gen);
            for (Person figlio : fam.getChildren(gc)) discendiGenerazioni(figlio, gc, gen + 1);
        }
    }

    // freccia indietro nella toolbar come quella hardware
    @Override
    public boolean onOptionsItemSelected(MenuItem i) {
        onBackPressed();
        return true;
    }
}

18 Source : DeviceView.java
with Apache License 2.0
from lemariva

public void addRowToTable(TableRow row) {
    if (first) {
        table.removeAllViews();
        table.addView(row);
        table.requestLayout();
        first = false;
    } else {
        table.addView(row);
        table.requestLayout();
    }
}

18 Source : TableBuilder.java
with Apache License 2.0
from iqiyi

/**
 * @param data : len can be more or less than cols count
 */
public void addRow(String rowName, String[] data) {
    if (layout != null) {
        int rowId = rowCount;
        rowCount++;
        TableRow row = new TableRow(layout.getContext());
        if (rowName != null) {
            View view = createRowNameView(layout.getContext(), row, rowId, rowName);
            row.addView(view);
        }
        inflateRowData(row, data, 0, rowId);
        layout.addView(row);
        // [avoid login er]
        if (mData == null) {
            mData = new String[0];
        }
        int len = mData.length;
        String[] nData = new String[len + colCount];
        int i = 0;
        for (; i < len; i++) {
            nData[i] = mData[i];
        }
        int dataLen = data == null ? 0 : data.length;
        for (int j = 0; j < colCount; j++) {
            if (j < dataLen) {
                nData[i++] = data[j];
            } else {
                nData[i++] = "";
            }
        }
        this.mData = nData;
    }
}

18 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

private View[] getContentCells(TableRow row) {
    View[] result = new View[5];
    for (int i = 0; i < 5; i++) result[i] = row.getChildAt(i);
    // element 1 is a scrollview with nested TextView
    result[2] = ((ViewGroup) result[2]).getChildAt(0);
    // element 2 is a scrollview with nested TextView
    result[3] = ((ViewGroup) result[3]).getChildAt(0);
    return result;
}

18 Source : TicTacToeActivity.java
with MIT License
from bridgefy

protected void resetBoard(int[][] board) {
    for (int i = 0; i < size; i++) {
        TableRow row = (TableRow) mainBoard.getChildAt(i);
        for (int j = 0; j < size; j++) {
            char c = board != null ? (char) board[i][j] : 0;
            this.board[i][j] = c;
            TextView tv = (TextView) row.getChildAt(j);
            switch(c) {
                case 'X':
                    tv.setText(R.string.X);
                    break;
                case 'O':
                    tv.setText(R.string.O);
                    break;
                default:
                    tv.setText(R.string.none);
                    break;
            }
        }
    }
}

17 Source : TripHistoryFragment.java
with Apache License 2.0
from underlx

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public clreplaced TripHistoryFragment extends TopFragment {

    private static final String ARG_COLUMN_COUNT = "column-count";

    private int mColumnCount = 1;

    private OnListFragmentInteractionListener mListener;

    private RecyclerView recyclerView = null;

    private TextView emptyView;

    private TextView tripCountView;

    private TextView tripTotalLengthView;

    private TextView tripTotalTimeView;

    private TextView tripAverageSpeedView;

    private TableRow posPlayLoadingRow;

    private TableRow posPlayRow1;

    private TableRow posPlayRow2;

    private ImageView posPlayAvatarView;

    private TextView posPlayUserView;

    private TextView posPlayLevelView;

    private ProgressBar posPlayLevelProgress;

    private TextView posPlayNextLevelView;

    private TextView posPlayOverallView;

    private TextView posPlayWeekView;

    private boolean showVisits = false;

    private Menu menu;

    /**
     * Mandatory constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TripHistoryFragment() {
    }

    @Override
    public boolean needsTopology() {
        return true;
    }

    @Override
    public int getNavDrawerId() {
        return R.id.nav_trip_history;
    }

    @Override
    public String getNavDrawerIdreplacedtring() {
        return "nav_trip_history";
    }

    @SuppressWarnings("unused")
    public static TripHistoryFragment newInstance(int columnCount) {
        TripHistoryFragment fragment = new TripHistoryFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setUpActivity(getString(R.string.frag_trip_history_replacedle), false, false);
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.fragment_trip_history_list, container, false);
        // Set the adapter
        Context context = view.getContext();
        emptyView = view.findViewById(R.id.no_trips_view);
        tripCountView = view.findViewById(R.id.trip_count_view);
        tripTotalLengthView = view.findViewById(R.id.trip_total_length_view);
        tripTotalTimeView = view.findViewById(R.id.trip_total_time_view);
        tripAverageSpeedView = view.findViewById(R.id.trip_average_speed_view);
        posPlayLoadingRow = view.findViewById(R.id.posplay_loading_row);
        posPlayRow1 = view.findViewById(R.id.posplay_row1);
        posPlayRow2 = view.findViewById(R.id.posplay_row2);
        posPlayAvatarView = view.findViewById(R.id.posplay_avatar_view);
        posPlayUserView = view.findViewById(R.id.posplay_user_view);
        posPlayLevelView = view.findViewById(R.id.posplay_level_view);
        posPlayLevelProgress = view.findViewById(R.id.posplay_level_progress);
        posPlayNextLevelView = view.findViewById(R.id.posplay_next_level_view);
        posPlayOverallView = view.findViewById(R.id.posplay_overall_view);
        posPlayWeekView = view.findViewById(R.id.posplay_week_view);
        Drawable progressDrawable = posPlayLevelProgress.getProgressDrawable().mutate();
        progressDrawable.setColorFilter(Color.parseColor("#0078E7"), android.graphics.PorterDuff.Mode.SRC_IN);
        posPlayLevelProgress.setProgressDrawable(progressDrawable);
        posPlayRow1.setOnClickListener(view1 -> {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.posplay_website)));
            startActivity(browserIntent);
        });
        recyclerView = view.findViewById(R.id.list);
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.addItemDecoration(new SimpleDividerItemDecoration(context));
        // fix scroll fling. less than ideal, but apparently there's still no other solution
        recyclerView.setNestedScrollingEnabled(false);
        view.findViewById(R.id.stats_button).setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), StatsActivity.clreplaced);
            startActivity(intent);
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.ACTION_MAIN_SERVICE_BOUND);
        filter.addAction(MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED);
        filter.addAction(MainService.ACTION_TRIP_TABLE_UPDATED);
        LocalBroadcastManager bm = LocalBroadcastManager.getInstance(context);
        bm.registerReceiver(mBroadcastReceiver, filter);
        new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.trip_history, menu);
        if (showVisits) {
            menu.findItem(R.id.menu_show_visits).setVisible(false);
        } else {
            menu.findItem(R.id.menu_hide_visits).setVisible(false);
        }
        this.menu = menu;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case R.id.menu_show_visits:
                showVisits = true;
                item.setVisible(false);
                menu.findItem(R.id.menu_hide_visits).setVisible(true);
                new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                return true;
            case R.id.menu_hide_visits:
                showVisits = false;
                item.setVisible(false);
                menu.findItem(R.id.menu_show_visits).setVisible(true);
                new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private clreplaced UpdateDataTask extends AsyncTask<Void, Integer, Boolean> {

        private List<TripRecyclerViewAdapter.TripItem> items = new ArrayList<>();

        private int tripCount = 0;

        private int tripTotalLength = 0;

        private int tripTotalTimeableLength = 0;

        private long tripTotalTime = 0;

        private long tripTotalMovementTime = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (isAdded()) {
                getSwipeRefreshLayout().setRefreshing(true);
            }
        }

        protected Boolean doInBackground(Void... v) {
            while (mListener == null || mListener.getMainService() == null) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
            Collection<Network> networks = Coordinator.get(getContext()).getMapManager().getNetworks();
            AppDatabase db = Coordinator.get(getContext()).getDB();
            for (Trip t : db.tripDao().getAll()) {
                try {
                    TripRecyclerViewAdapter.TripItem item = new TripRecyclerViewAdapter.TripItem(db, t, networks);
                    if (!item.isVisit) {
                        tripCount++;
                        tripTotalLength += item.length;
                        tripTotalTimeableLength += item.timeableLength;
                        tripTotalTime += item.destTime.getTime() - item.originTime.getTime();
                        tripTotalMovementTime += item.movementMilliseconds;
                    }
                    if (showVisits || !item.isVisit) {
                        items.add(item);
                    }
                } catch (InvalidObjectException e) {
                    e.printStackTrace();
                }
            }
            if (items.size() == 0) {
                return false;
            }
            Collections.sort(items, Collections.<TripRecyclerViewAdapter.TripItem>reverseOrder((tripItem, t1) -> Long.valueOf(tripItem.originTime.getTime()).compareTo(Long.valueOf(t1.originTime.getTime()))));
            return true;
        }

        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(Boolean result) {
            if (!isAdded()) {
                // prevent onPostExecute from doing anything if no longer attached to an activity
                return;
            }
            tripCountView.setText(String.format("%d", tripCount));
            tripTotalLengthView.setText(String.format(getString(R.string.frag_trip_history_length_value), (double) tripTotalLength / 1000f));
            long days = tripTotalTime / TimeUnit.DAYS.toMillis(1);
            long hours = (tripTotalTime % TimeUnit.DAYS.toMillis(1)) / TimeUnit.HOURS.toMillis(1);
            long minutes = (tripTotalTime % TimeUnit.HOURS.toMillis(1)) / TimeUnit.MINUTES.toMillis(1);
            if (days == 0) {
                tripTotalTimeView.setText(String.format(getString(R.string.frag_trip_history_duration_no_days), hours, minutes));
            } else {
                tripTotalTimeView.setText(String.format(getString(R.string.frag_trip_history_duration_with_days), days, hours, minutes));
            }
            tripAverageSpeedView.setText("--");
            if (recyclerView != null && mListener != null) {
                recyclerView.setAdapter(new TripRecyclerViewAdapter(items, mListener));
                recyclerView.invalidate();
                if (result) {
                    emptyView.setVisibility(View.GONE);
                    if (tripTotalMovementTime > 0) {
                        tripAverageSpeedView.setText(String.format(getString(R.string.frag_trip_history_speed_value), ((double) tripTotalTimeableLength / (double) (tripTotalMovementTime / 1000)) * 3.6));
                    }
                } else {
                    emptyView.setVisibility(View.VISIBLE);
                }
            } else {
                emptyView.setVisibility(View.VISIBLE);
            }
            new UpdatePosPlayTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            getSwipeRefreshLayout().setRefreshing(false);
        }
    }

    private final static String POSPLAY_CACHE_KEY = "PosPlayStatus";

    private clreplaced UpdatePosPlayTask extends AsyncTask<Void, Void, Boolean> {

        private API.PosPlayStatus status;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            posPlayLoadingRow.setVisibility(View.VISIBLE);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            CacheManager cm = Coordinator.get(getContext()).getCacheManager();
            status = cm.fetchOrGet(POSPLAY_CACHE_KEY, (key, storeDate) -> false, key -> {
                try {
                    List<API.PairConnection> connections = API.getInstance().getPairConnections();
                    for (API.PairConnection connection : connections) {
                        if (connection.service.equals("posplay")) {
                            API.PosPlayStatus status = API.getInstance().getMapper().convertValue(connection.extra, API.PosPlayStatus.clreplaced);
                            if (status != null) {
                                status.serviceName = connection.serviceName;
                            }
                            return status;
                        }
                    }
                    // if we got here, there's no PosPlay connection (device may have been unpaired)
                    // so delete key to ensure we don't show PosPlay info anymore
                    cm.remove(POSPLAY_CACHE_KEY);
                } catch (IllegalArgumentException e) {
                    // convertValue throws
                    return null;
                } catch (APIException e) {
                    return null;
                }
                return null;
            }, API.PosPlayStatus.clreplaced);
            return status != null;
        }

        protected void onPostExecute(Boolean result) {
            if (!isAdded()) {
                // prevent onPostExecute from doing anything if no longer attached to an activity
                return;
            }
            posPlayLoadingRow.setVisibility(View.GONE);
            if (result) {
                posPlayRow1.setVisibility(View.VISIBLE);
                posPlayRow2.setVisibility(View.VISIBLE);
                String userLine = String.format(getString(R.string.frag_trip_history_posplay_username), status.username, status.serviceName);
                int nStart = userLine.indexOf(status.username);
                int nEnd = nStart + status.username.length();
                SpannableString userSpannable = new SpannableString(userLine);
                userSpannable.setSpan(new StyleSpan(Typeface.BOLD), nStart, nEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                posPlayUserView.setText(userSpannable);
                String levelAlone = String.format("%d", status.level);
                String levelLine = String.format(getString(R.string.frag_trip_history_posplay_level), status.level);
                int lStart = levelLine.indexOf(levelAlone);
                int lEnd = lStart + levelAlone.length();
                SpannableString levelSpannable = new SpannableString(levelLine);
                levelSpannable.setSpan(new StyleSpan(Typeface.BOLD), lStart, lEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                posPlayLevelView.setText(levelSpannable);
                posPlayLevelProgress.setProgress(Math.round(status.levelProgress));
                posPlayNextLevelView.setText(String.format("%d", status.level + 1));
                // all-time info
                String placeLine;
                boolean placeWordIsFemale = false;
                switch(Util.getCurrentLanguage(getContext())) {
                    case "es":
                    case "fr":
                        placeWordIsFemale = true;
                        break;
                }
                if (status.rank == 0) {
                    placeLine = getString(R.string.frag_trip_history_posplay_no_participation);
                } else {
                    placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place), status.xp, Util.getOrdinal(getContext(), status.rank, placeWordIsFemale));
                }
                Spannable placeSpannable = new SpannableString(placeLine);
                if (status.rank == 1) {
                    placeSpannable.setSpan(new ForegroundColorSpan(Color.parseColor("#DAA520")), placeLine.indexOf("\n"), placeLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                posPlayOverallView.setText(placeSpannable);
                // week info
                if (status.rankThisWeek == 0) {
                    placeLine = getString(R.string.frag_trip_history_posplay_no_participation);
                } else {
                    placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place), status.xpThisWeek, Util.getOrdinal(getContext(), status.rankThisWeek, placeWordIsFemale));
                }
                placeSpannable = new SpannableString(placeLine);
                if (status.rankThisWeek == 1) {
                    placeSpannable.setSpan(new ForegroundColorSpan(Color.parseColor("#DAA520")), placeLine.indexOf("\n"), placeLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                posPlayWeekView.setText(placeSpannable);
                RequestCreator rc = Picreplacedo.get().load(status.avatarURL);
                if (!Connectivity.isConnectedWifi(getContext())) {
                    rc.networkPolicy(NetworkPolicy.OFFLINE);
                }
                rc.transform(new CircleTransform()).into(posPlayAvatarView);
            } else {
                posPlayRow1.setVisibility(View.GONE);
                posPlayRow2.setVisibility(View.GONE);
            }
        }
    }

    public clreplaced CircleTransform implements Transformation {

        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
            Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
            if (squaredBitmap != source) {
                source.recycle();
            }
            Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            paint.setShader(shader);
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            squaredBitmap.recycle();
            return bitmap;
        }

        @Override
        public String key() {
            return "circle";
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener extends OnInteractionListener, TripRecyclerViewAdapter.OnListFragmentInteractionListener {
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch(intent.getAction()) {
                case MainActivity.ACTION_MAIN_SERVICE_BOUND:
                case MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED:
                case MainService.ACTION_TRIP_TABLE_UPDATED:
                    if (getActivity() != null && isAdded()) {
                        new UpdateDataTask().executeOnExecutor(Util.LARGE_STACK_THREAD_POOL_EXECUTOR);
                    }
                    break;
            }
        }
    };
}

17 Source : StatisticsFragment.java
with GNU General Public License v3.0
from TobiasBielefeld

/**
 * Shows the high scores of the current game
 */
public clreplaced StatisticsFragment extends Fragment {

    private TextView textWonGames, textWinPercentage, textAdditionalStatisticsreplacedle, textAdditionalStatisticsValue, textTotalTimePlayed, textTotalPointsEarned, textTotalHintsShown, textTotalNumberUndos;

    private CardView winPercentageCardView;

    private TableRow tableRowAdditionalText;

    /**
     * Loads the high score list
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_statistics_tab1, container, false);
        winPercentageCardView = view.findViewById(R.id.statisticsCardViewWinPercentage);
        textWonGames = view.findViewById(R.id.statisticsTextViewGamesWon);
        textWinPercentage = view.findViewById(R.id.statisticsTextViewWinPercentage);
        textAdditionalStatisticsreplacedle = view.findViewById(R.id.statisticsAdditionalText);
        textAdditionalStatisticsValue = view.findViewById(R.id.statisticsAdditionalTextValue);
        textTotalTimePlayed = view.findViewById(R.id.statisticsTotalTimePlayed);
        textTotalPointsEarned = view.findViewById(R.id.statisticsTotalPointsEarned);
        textTotalHintsShown = view.findViewById(R.id.statisticsTotalHintsShown);
        textTotalNumberUndos = view.findViewById(R.id.statisticsTotalUndoMovements);
        tableRowAdditionalText = view.findViewById(R.id.statisticsAdditionalRow);
        // if the app got killed while the statistics are open and then the user restarts the app,
        // my helper clreplacedes aren't initialized so they can't be used. In this case, simply
        // close the statistics
        try {
            loadData();
        } catch (NullPointerException e) {
            getActivity().finish();
            return view;
        }
        ((StatisticsActivity) getActivity()).setCallback(this::updateWinPercentageView);
        winPercentageCardView.setVisibility(prefs.getSavedStatisticsHideWinPercentage() ? View.GONE : View.VISIBLE);
        return view;
    }

    /**
     * loads the other shown data
     */
    private void loadData() {
        int wonGames = prefs.getSavedNumberOfWonGames();
        int totalGames = prefs.getSavedNumberOfPlayedGames();
        int totalHintsShown = prefs.getSavedTotalHintsShown();
        int totalNumberUndos = prefs.getSavedTotalNumberUndos();
        long totalTime = prefs.getSavedTotalTimePlayed();
        long totalPoints = prefs.getSavedTotalPointsEarned();
        textWonGames.setText(String.format(Locale.getDefault(), getString(R.string.statistics_text_won_games), wonGames, totalGames));
        textWinPercentage.setText(String.format(Locale.getDefault(), getString(R.string.statistics_win_percentage), totalGames > 0 ? ((float) wonGames * 100 / totalGames) : 0.0));
        textTotalTimePlayed.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", totalTime / 3600, (totalTime % 3600) / 60, totalTime % 60));
        textTotalHintsShown.setText(String.format(Locale.getDefault(), "%d", totalHintsShown));
        textTotalNumberUndos.setText(String.format(Locale.getDefault(), "%d", totalNumberUndos));
        textTotalPointsEarned.setText(String.format(Locale.getDefault(), currentGame.isPointsInDollar() ? "%d $" : "%d", totalPoints));
        boolean added = currentGame.setAdditionalStatisticsData(getResources(), textAdditionalStatisticsreplacedle, textAdditionalStatisticsValue);
        if (added) {
            tableRowAdditionalText.setVisibility(View.VISIBLE);
        }
    }

    private void updateWinPercentageView(boolean hide) {
        if (winPercentageCardView != null) {
            winPercentageCardView.setVisibility(hide ? View.GONE : View.VISIBLE);
        }
    }
}

17 Source : WorkoutSettingsFragment.java
with GNU General Public License v3.0
from oliexdev

public clreplaced WorkoutSettingsFragment extends GenericSettingsFragment {

    private Workoureplacedem workoureplacedem;

    private ImageView imgView;

    private TextView nameView;

    private TextView descriptionView;

    private TextView prepTimeView;

    private TextView workoutTimeView;

    private TextView breakTimeView;

    private TextView repereplacedionCountView;

    private Switch timeModeView;

    private TableRow workoutTimeRow;

    private TableRow repereplacedionCountRow;

    private Switch videoModeView;

    private TableRow videoCardRow;

    private CardView videoCardView;

    private VideoView videoView;

    private FileDialogHelper fileDialogHelper;

    private boolean isImageDialogRequest;

    public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_workoutsettings, container, false);
        fileDialogHelper = new FileDialogHelper(this);
        imgView = root.findViewById(R.id.imgView);
        nameView = root.findViewById(R.id.nameView);
        descriptionView = root.findViewById(R.id.descriptionView);
        prepTimeView = root.findViewById(R.id.prepTimeView);
        workoutTimeView = root.findViewById(R.id.workoutTimeView);
        breakTimeView = root.findViewById(R.id.breakTimeView);
        repereplacedionCountView = root.findViewById(R.id.repereplacedionCountView);
        timeModeView = root.findViewById(R.id.timeModeView);
        workoutTimeRow = root.findViewById(R.id.workoutTimeRow);
        repereplacedionCountRow = root.findViewById(R.id.repereplacedionCountRow);
        videoModeView = root.findViewById(R.id.videoModeView);
        videoCardRow = root.findViewById(R.id.videoCardRow);
        videoCardView = root.findViewById(R.id.videoCardView);
        videoView = root.findViewById(R.id.videoView);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
        timeModeView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                workoureplacedem.setTimeMode(isChecked);
                refreshTimeModeState();
            }
        });
        videoModeView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                workoureplacedem.setVideoMode(isChecked);
                refreshVideoModeState();
            }
        });
        imgView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                isImageDialogRequest = true;
                fileDialogHelper.openImageFileDialog();
            }
        });
        // support for SDK version <= 23 videoView onClickListener is not called
        videoCardView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                isImageDialogRequest = false;
                fileDialogHelper.openVideoFileDialog();
            }
        });
        videoView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                isImageDialogRequest = false;
                fileDialogHelper.openVideoFileDialog();
            }
        });
        setMode(WorkoutSettingsFragmentArgs.fromBundle(getArguments()).getMode());
        return root;
    }

    @Override
    protected String getreplacedle() {
        return workoureplacedem.getName();
    }

    @Override
    protected void loadFromDatabase(SETTING_MODE mode) {
        long workoureplacedemId = WorkoutSettingsFragmentArgs.fromBundle(getArguments()).getWorkoureplacedemId();
        switch(mode) {
            case ADD:
                if (workoureplacedemId != -1L) {
                    workoureplacedem = OpenWorkout.getInstance().getWorkoureplacedem(workoureplacedemId).clone();
                    workoureplacedem.setWorkoureplacedemId(0);
                } else {
                    workoureplacedem = new Workoureplacedem();
                }
                break;
            case EDIT:
                workoureplacedem = OpenWorkout.getInstance().getWorkoureplacedem(workoureplacedemId);
                break;
        }
        try {
            if (workoureplacedem.isImagePathExternal()) {
                imgView.setImageURI(Uri.parse(workoureplacedem.getImagePath()));
            } else {
                String subFolder;
                if (OpenWorkout.getInstance().getCurrentUser().isMale()) {
                    subFolder = "male";
                } else {
                    subFolder = "female";
                }
                InputStream ims = getContext().getreplacedets().open("image/" + subFolder + "/" + workoureplacedem.getImagePath());
                imgView.setImageDrawable(Drawable.createFromStream(ims, null));
                ims.close();
            }
        } catch (IOException ex) {
            Timber.e(ex);
        } catch (SecurityException ex) {
            imgView.setImageResource(R.drawable.ic_no_file);
            Toast.makeText(getContext(), getContext().getString(R.string.error_no_access_to_file) + " " + workoureplacedem.getImagePath(), Toast.LENGTH_SHORT).show();
            Timber.e(ex);
        }
        try {
            if (workoureplacedem.isVideoPathExternal()) {
                videoView.setVideoURI(Uri.parse(workoureplacedem.getVideoPath()));
            } else {
                if (OpenWorkout.getInstance().getCurrentUser().isMale()) {
                    videoView.setVideoPath("content://com.health.openworkout.videoprovider/video/male/" + workoureplacedem.getVideoPath());
                } else {
                    videoView.setVideoPath("content://com.health.openworkout.videoprovider/video/female/" + workoureplacedem.getVideoPath());
                }
            }
        } catch (SecurityException ex) {
            videoView.setVideoURI(null);
            Toast.makeText(getContext(), getContext().getString(R.string.error_no_access_to_file) + " " + workoureplacedem.getVideoPath(), Toast.LENGTH_SHORT).show();
            Timber.e(ex);
        }
        videoView.start();
        nameView.setText(workoureplacedem.getName());
        descriptionView.setText(workoureplacedem.getDescription());
        prepTimeView.setText(Integer.toString(workoureplacedem.getPrepTime()));
        workoutTimeView.setText(Integer.toString(workoureplacedem.getWorkoutTime()));
        breakTimeView.setText(Integer.toString(workoureplacedem.getBreakTime()));
        repereplacedionCountView.setText(Integer.toString(workoureplacedem.getRepereplacedionCount()));
        videoModeView.setChecked(workoureplacedem.isVideoMode());
        timeModeView.setChecked(workoureplacedem.isTimeMode());
        refreshTimeModeState();
        refreshVideoModeState();
    }

    private void refreshTimeModeState() {
        if (workoureplacedem.isTimeMode()) {
            workoutTimeRow.setVisibility(View.VISIBLE);
            repereplacedionCountRow.setVisibility(View.GONE);
        } else {
            workoutTimeRow.setVisibility(View.GONE);
            repereplacedionCountRow.setVisibility(View.VISIBLE);
        }
    }

    private void refreshVideoModeState() {
        if (workoureplacedem.isVideoMode()) {
            videoCardRow.setVisibility(View.VISIBLE);
        } else {
            videoCardRow.setVisibility(View.GONE);
        }
    }

    @Override
    protected boolean saveToDatabase(SETTING_MODE mode) {
        boolean checkFormat = true;
        workoureplacedem.setName(nameView.getText().toString());
        workoureplacedem.setDescription(descriptionView.getText().toString());
        if (prepTimeView.getText().toString().isEmpty()) {
            prepTimeView.setError(getString(R.string.error_empty_text));
            checkFormat = false;
        } else {
            workoureplacedem.setPrepTime(Integer.valueOf(prepTimeView.getText().toString()));
        }
        if (workoutTimeView.getText().toString().isEmpty()) {
            workoutTimeView.setError(getString(R.string.error_empty_text));
            checkFormat = false;
        } else {
            workoureplacedem.setWorkoutTime(Integer.valueOf(workoutTimeView.getText().toString()));
        }
        if (breakTimeView.getText().toString().isEmpty()) {
            breakTimeView.setError(getString(R.string.error_empty_text));
            checkFormat = false;
        } else {
            workoureplacedem.setBreakTime(Integer.valueOf(breakTimeView.getText().toString()));
        }
        if (repereplacedionCountView.getText().toString().isEmpty()) {
            repereplacedionCountView.setError(getString(R.string.error_empty_text));
            checkFormat = false;
        } else {
            workoureplacedem.setRepereplacedionCount(Integer.valueOf(repereplacedionCountView.getText().toString()));
        }
        workoureplacedem.setTimeMode(timeModeView.isChecked());
        workoureplacedem.setVideoMode(videoModeView.isChecked());
        switch(mode) {
            case ADD:
                long workoutSessionId = WorkoutSettingsFragmentArgs.fromBundle(getArguments()).getSessionWorkoutId();
                workoureplacedem.setWorkoutSessionId(workoutSessionId);
                workoureplacedem.setOrderNr(OpenWorkout.getInstance().getWorkoutSession(workoutSessionId).getWorkoureplacedems().size() + 1);
                OpenWorkout.getInstance().insertWorkoureplacedem(workoureplacedem);
                Navigation.findNavController(getActivity(), R.id.nav_host_fragment).navigateUp();
                break;
            case EDIT:
                OpenWorkout.getInstance().updateWorkoureplacedem(workoureplacedem);
                break;
        }
        return checkFormat;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        fileDialogHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (fileDialogHelper.onActivityResult(requestCode, resultCode, data)) {
            Uri uri = data.getData();
            if (isImageDialogRequest) {
                imgView.setImageURI(uri);
                workoureplacedem.setImagePath(uri.toString());
                workoureplacedem.setImagePathExternal(true);
            } else {
                videoView.setVideoURI(uri);
                videoView.start();
                workoureplacedem.setVideoPath(uri.toString());
                workoureplacedem.setVideoPathExternal(true);
            }
        }
    }
}

17 Source : TableBuilder.java
with Apache License 2.0
from iqiyi

private View createRowNameView(Context context, TableRow rowParent, int rowId, String name) {
    View itemView;
    if (binder != null) {
        itemView = binder.createItemView(rowParent, rowId, -1);
        binder.bindData(name, itemView, rowId, -1);
    } else {
        TextView textView = createDefaulreplacedemView(context, namesTextSize, namesTextColor);
        textView.setText(name);
        itemView = textView;
    }
    return itemView;
}

17 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

private void showEditDialog(TableRow row) {
    editedRow = row;
    View[] currentContent = getContentCells(editedRow);
    ((CheckBox) editDialog.findViewById(R.id.activeChk)).setChecked(((CheckBox) currentContent[0]).isChecked());
    ((TextView) editDialog.findViewById(R.id.filterCategory)).setText(((TextView) currentContent[1]).getText().toString());
    ((TextView) editDialog.findViewById(R.id.filterName)).setText(((TextView) currentContent[2]).getText().toString());
    ((TextView) editDialog.findViewById(R.id.filterUrl)).setText(((TextView) currentContent[3]).getText().toString());
    editDialog.show();
    WindowManager.LayoutParams lp = editDialog.getWindow().getAttributes();
    lp.width = (int) (configTable.getContext().getResources().getDisplayMetrics().widthPixels * 1.00);
    ;
    editDialog.getWindow().setAttributes(lp);
}

17 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

public void clear() {
    filterEntries = getFilterEntries();
    int count = configTable.getChildCount() - 1;
    for (int i = count; i > 0; i--) {
        TableRow row = (TableRow) configTable.getChildAt(i);
        row.getChildAt(4).setOnClickListener(null);
        configTable.removeView(row);
    }
    categoryDown.setOnClickListener(null);
    categoryUp.setOnClickListener(null);
    loaded = false;
}

17 Source : MultiLineRadioGroup.java
with MIT License
from Gavras

// removes the redundant rows and radio buttons
private void removeRedundancies() {
    // the number of rows to fit the buttons
    int rows;
    if (mRadioButtons.size() == 0)
        rows = 0;
    else if (mMaxInRow == 0)
        rows = 1;
    else
        rows = (mRadioButtons.size() - 1) / mMaxInRow + 1;
    int tableChildCount = mTableLayout.getChildCount();
    // if there are redundant rows remove them
    if (tableChildCount > rows)
        mTableLayout.removeViews(rows, tableChildCount - rows);
    tableChildCount = mTableLayout.getChildCount();
    int maxInRow = (mMaxInRow != 0) ? mMaxInRow : mRadioButtons.size();
    // iterates over the rows
    for (int i = 0; i < tableChildCount; i++) {
        TableRow tableRow = (TableRow) mTableLayout.getChildAt(i);
        int tableRowChildCount = tableRow.getChildCount();
        int startIndexToRemove;
        int count;
        // if it is the last row removes all redundancies after the last button in the list
        if (i == tableChildCount - 1) {
            startIndexToRemove = (mRadioButtons.size() - 1) % maxInRow + 1;
            count = tableRowChildCount - startIndexToRemove;
        // if it is not the last row removes all the buttons after maxInRow position
        } else {
            startIndexToRemove = maxInRow;
            count = tableRowChildCount - maxInRow;
        }
        if (count > 0)
            tableRow.removeViews(startIndexToRemove, count);
    }
}

17 Source : MovesetFraction.java
with GNU General Public License v3.0
from farkam135

private void buildRow(MovesetData move, TableRow recycle) {
    TableRow row;
    RowViewHolder holder;
    if (recycle != null) {
        row = recycle;
        holder = (RowViewHolder) row.getTag();
    } else {
        row = (TableRow) LayoutInflater.from(pokefly).inflate(R.layout.table_row_moveset, tableLayout, false);
        holder = new RowViewHolder();
        row.setTag(holder);
    }
    holder.bind(row, move);
    if (row.getParent() == null) {
        tableLayout.addView(row);
    }
}

17 Source : ActFlightQuery.java
with GNU General Public License v3.0
from ericberman

private void setUpDynamicCheckList(int idTable, Object[] rgItems, CheckedTableListener listener) {
    TableLayout tl = (TableLayout) findViewById(idTable);
    if (tl == null)
        return;
    tl.removeAllViews();
    LayoutInflater l = requireActivity().getLayoutInflater();
    replacedert listener != null;
    if (rgItems == null)
        rgItems = new Object[0];
    for (Object o : rgItems) {
        TableRow tr = (TableRow) l.inflate(R.layout.checkboxtableitem, tl, false);
        final Object oFinal = o;
        CheckBox ck = tr.findViewById(R.id.checkbox);
        ck.setText(o.toString());
        ck.setChecked(listener.itemIsChecked(o));
        ck.setOnCheckedChangeListener((compoundButton, fChecked) -> listener.itemStateChanged(oFinal, fChecked));
        tl.addView(tr, new TableLayout.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
    }
}

17 Source : TableLayout.java
with GNU General Public License v2.0
from Cloudslab

void setNumColumns(int newNumColumns) {
    int row;
    if (newNumColumns > this.numColumns) {
        Context context = this.layoutManager.getContext();
        for (row = 0; row < this.numRows; row++) {
            TableRow tableRow = (TableRow) this.layoutManager.getChildAt(row);
            for (int col = this.numColumns; col < newNumColumns; col++) {
                tableRow.addView(newEmptyCellView(), col, newEmptyCellLayoutParams());
            }
        }
        this.numColumns = newNumColumns;
    } else if (newNumColumns < this.numColumns) {
        for (row = 0; row < this.numRows; row++) {
            ((TableRow) this.layoutManager.getChildAt(row)).removeViews(newNumColumns, this.numColumns - newNumColumns);
        }
        this.numColumns = newNumColumns;
    }
}

17 Source : TableLayout.java
with GNU General Public License v2.0
from Cloudslab

void setNumRows(int newNumRows) {
    if (newNumRows > this.numRows) {
        Context context = this.layoutManager.getContext();
        for (int row = this.numRows; row < newNumRows; row++) {
            TableRow tableRow = new TableRow(context);
            for (int col = 0; col < this.numColumns; col++) {
                tableRow.addView(newEmptyCellView(), col, newEmptyCellLayoutParams());
            }
            this.layoutManager.addView(tableRow, row, new LayoutParams());
        }
        this.numRows = newNumRows;
    } else if (newNumRows < this.numRows) {
        this.layoutManager.removeViews(newNumRows, this.numRows - newNumRows);
        this.numRows = newNumRows;
    }
}

17 Source : GnssStatusFragment.java
with Apache License 2.0
from christianrowlands

/**
 * A fragment for displaying the latest GNSS information to the user.
 * <p>
 * This interface is originally from the GPS Test open source Android app and has been adapted to meet the needs of
 * this Network Survey app.
 * https://github.com/barbeau/gpstest/blob/master/GPSTest/src/main/java/com/android/gpstest/GpsStatusFragment.java
 */
public clreplaced GnssStatusFragment extends Fragment implements IGnssListener {

    static final String replacedLE = "Details";

    private static final String EMPTY_LAT_LONG = "             ";

    /*TODO We either need to fix everything to a specific unit of measurement, or update the Settings UI to allow the user to control it.
    private static final String METERS = Application.get().getResources().getStringArray(R.array.preferred_distance_units_values)[0];
    private static final String METERS_PER_SECOND = Application.get().getResources().getStringArray(R.array.preferred_speed_units_values)[0];
    private static final String KILOMETERS_PER_HOUR = Application.get().getResources().getStringArray(R.array.preferred_speed_units_values)[1];*/
    private static final String METERS = "1";

    private static final String METERS_PER_SECOND = "1";

    private static final String KILOMETERS_PER_HOUR = "2";

    private SimpleDateFormat dateFormat;

    private Resources resources;

    private TextView lareplacedudeView, longitudeView, fixTimeView, ttffView, alreplacedudeView, alreplacedudeMslView, horVertAccuracyLabelView, horVertAccuracyView, speedView, speedAccuracyView, bearingView, bearingAccuracyView, numSats, pdopLabelView, pdopView, hvdopLabelView, hvdopView, gnssNotAvailableView, sbasNotAvailableView;

    private Location latestLocation;

    private TableRow speedBearingAccuracyRow;

    private RecyclerView gnssStatusList;

    private RecyclerView sbreplacedtatusList;

    private SatelliteStatusAdapter gnssAdapter;

    private SatelliteStatusAdapter sbasAdapter;

    private List<SatelliteStatus> gnssStatus = new ArrayList<>();

    private List<SatelliteStatus> sbreplacedtatus = new ArrayList<>();

    private int svCount;

    private String snrCn0replacedle;

    private long fixTime;

    private boolean navigating;

    private Drawable flagUsa;

    private Drawable flagRussia;

    private Drawable flagreplacedan;

    private Drawable flagChina;

    private Drawable flagIndia;

    private Drawable flagEu;

    private Drawable flagIcao;

    private String ttff = "";

    private String prefDistanceUnits;

    private String prefSpeedUnits;

    private final MainGnssFragment mainGnssFragment;

    /**
     * Constructs this fragment.
     *
     * @param mainGnssFragment Used to register and unregister for updates to GNSS events.
     */
    GnssStatusFragment(MainGnssFragment mainGnssFragment) {
        this.mainGnssFragment = mainGnssFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dateFormat = new SimpleDateFormat(DateFormat.is24HourFormat(getContext()) ? "HH:mm:ss" : "hh:mm:ss a", Locale.getDefault());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        resources = getResources();
        setupUnitPreferences();
        View v = inflater.inflate(R.layout.gps_status, container, false);
        lareplacedudeView = v.findViewById(R.id.lareplacedude);
        longitudeView = v.findViewById(R.id.longitude);
        fixTimeView = v.findViewById(R.id.fix_time);
        ttffView = v.findViewById(R.id.ttff);
        alreplacedudeView = v.findViewById(R.id.alreplacedude);
        alreplacedudeMslView = v.findViewById(R.id.alreplacedude_msl);
        horVertAccuracyLabelView = v.findViewById(R.id.hor_vert_accuracy_label);
        horVertAccuracyView = v.findViewById(R.id.hor_vert_accuracy);
        speedView = v.findViewById(R.id.speed);
        speedAccuracyView = v.findViewById(R.id.speed_acc);
        bearingView = v.findViewById(R.id.bearing);
        bearingAccuracyView = v.findViewById(R.id.bearing_acc);
        numSats = v.findViewById(R.id.num_sats);
        pdopLabelView = v.findViewById(R.id.pdop_label);
        pdopView = v.findViewById(R.id.pdop);
        hvdopLabelView = v.findViewById(R.id.hvdop_label);
        hvdopView = v.findViewById(R.id.hvdop);
        speedBearingAccuracyRow = v.findViewById(R.id.speed_bearing_acc_row);
        gnssNotAvailableView = v.findViewById(R.id.gnss_not_available);
        sbasNotAvailableView = v.findViewById(R.id.sbas_not_available);
        lareplacedudeView.setText(EMPTY_LAT_LONG);
        longitudeView.setText(EMPTY_LAT_LONG);
        final Context context = getContext();
        Resources.Theme theme = null;
        if (context != null)
            theme = context.getTheme();
        flagUsa = resources.getDrawable(R.drawable.ic_flag_usa, theme);
        flagRussia = resources.getDrawable(R.drawable.ic_flag_russia, theme);
        flagreplacedan = resources.getDrawable(R.drawable.ic_flag_replacedan, theme);
        flagChina = resources.getDrawable(R.drawable.ic_flag_china, theme);
        flagIndia = resources.getDrawable(R.drawable.ic_flag_india, theme);
        flagEu = resources.getDrawable(R.drawable.ic_flag_european_union, theme);
        flagIcao = resources.getDrawable(R.drawable.ic_flag_icao, theme);
        v.findViewById(R.id.status_location_card).setOnClickListener(view -> {
            // Copy location to clipboard
            if (latestLocation != null) {
                boolean includeAlreplacedude = Application.getPrefs().getBoolean(Application.get().getString(R.string.pref_key_share_include_alreplacedude), false);
                String coordinateFormat = Application.getPrefs().getString(Application.get().getString(R.string.pref_key_coordinate_format), Application.get().getString(R.string.preferences_coordinate_format_dd_key));
                String formattedLocation = UIUtils.formatLocationForDisplay(latestLocation, null, includeAlreplacedude, null, null, null, coordinateFormat);
                IOUtils.copyToClipboard(formattedLocation);
                Toast.makeText(getActivity(), R.string.copied_to_clipboard, Toast.LENGTH_LONG).show();
            }
        });
        // GNSS
        LinearLayoutManager llmGnss = new LinearLayoutManager(getContext());
        llmGnss.setOrientation(RecyclerView.VERTICAL);
        gnssStatusList = v.findViewById(R.id.gnss_status_list);
        gnssAdapter = new SatelliteStatusAdapter(GNSS);
        gnssStatusList.setAdapter(gnssAdapter);
        gnssStatusList.setFocusable(false);
        gnssStatusList.setFocusableInTouchMode(false);
        gnssStatusList.setLayoutManager(llmGnss);
        gnssStatusList.setNestedScrollingEnabled(false);
        // SBAS
        LinearLayoutManager llmSbas = new LinearLayoutManager(getContext());
        llmSbas.setOrientation(RecyclerView.VERTICAL);
        sbreplacedtatusList = v.findViewById(R.id.sbas_status_list);
        sbasAdapter = new SatelliteStatusAdapter(SBAS);
        sbreplacedtatusList.setAdapter(sbasAdapter);
        sbreplacedtatusList.setFocusable(false);
        sbreplacedtatusList.setFocusableInTouchMode(false);
        sbreplacedtatusList.setLayoutManager(llmSbas);
        sbreplacedtatusList.setNestedScrollingEnabled(false);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onResume() {
        Timber.d("Resuming the GNSS Status Fragment");
        super.onResume();
        mainGnssFragment.registerGnssListener(this);
        setupUnitPreferences();
    }

    @Override
    public void onPause() {
        Timber.d("Pausing the GNSS Status Fragment");
        mainGnssFragment.unregisterGnssListener(this);
        super.onPause();
    }

    /*TODO Should we add the menu for sorting?
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        inflater.inflate(R.menu.status_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        final int id = item.gereplacedemId();
        if (id == R.id.sort_sats)
        {
            showSortByDialog();
        }
        return false;
    }*/
    @Override
    public void onGnssFirstFix(int ttffMillis) {
        ttff = UIUtils.getTtffString(ttffMillis);
        if (ttffView != null) {
            ttffView.setText(ttff);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onSatelliteStatusChanged(GnssStatus status) {
        updateGnssStatus(status);
    }

    @Override
    public void onGnssStarted() {
        setStarted(true);
    }

    @Override
    public void onGnssStopped() {
        setStarted(false);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onGnssMeasurementsReceived(GnssMeasurementsEvent event) {
    // No-op
    }

    @Override
    public void onNmeaMessage(String message, long timestamp) {
        if (!isAdded()) {
            // Do nothing if the Fragment isn't added
            return;
        }
        if (message.startsWith("$GPGGA") || message.startsWith("$GNGNS") || message.startsWith("$GNGGA")) {
            Double alreplacedudeMsl = NmeaUtils.getAlreplacedudeMeanSeaLevel(message);
            if (alreplacedudeMsl != null && navigating) {
                if (prefDistanceUnits.equalsIgnoreCase(METERS)) {
                    alreplacedudeMslView.setText(resources.getString(R.string.gps_alreplacedude_msl_value_meters, alreplacedudeMsl));
                } else {
                    alreplacedudeMslView.setText(resources.getString(R.string.gps_alreplacedude_msl_value_feet, UIUtils.toFeet(alreplacedudeMsl)));
                }
            }
        }
        if (message.startsWith("$GNGSA") || message.startsWith("$GPGSA")) {
            DilutionOfPrecision dop = NmeaUtils.getDop(message);
            if (dop != null && navigating) {
                showDopViews();
                pdopView.setText(resources.getString(R.string.pdop_value, dop.getPositionDop()));
                hvdopView.setText(resources.getString(R.string.hvdop_value, dop.getHorizontalDop(), dop.getVerticalDop()));
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        if (!UIUtils.isFragmentAttached(this)) {
            // Fragment isn't visible, so return to avoid IllegalStateException (see #85)
            return;
        }
        // Cache location for copy to clipboard operation
        latestLocation = location;
        // Make sure TTFF is shown, if the TTFF is acquired before the mTTFFView is initialized
        ttffView.setText(ttff);
        String coordinateFormat = Application.getPrefs().getString(getString(R.string.pref_key_coordinate_format), getString(R.string.preferences_coordinate_format_dd_key));
        switch(coordinateFormat) {
            // Constants below must match string values in do_not_translate.xml
            case "dms":
                // Degrees minutes seconds
                lareplacedudeView.setText(UIUtils.getDMSFromLocation(Application.get(), location.getLareplacedude(), UIUtils.COORDINATE_LAreplacedUDE));
                longitudeView.setText(UIUtils.getDMSFromLocation(Application.get(), location.getLongitude(), UIUtils.COORDINATE_LONGITUDE));
                break;
            case "ddm":
                // Degrees decimal minutes
                lareplacedudeView.setText(UIUtils.getDDMFromLocation(Application.get(), location.getLareplacedude(), UIUtils.COORDINATE_LAreplacedUDE));
                longitudeView.setText(UIUtils.getDDMFromLocation(Application.get(), location.getLongitude(), UIUtils.COORDINATE_LONGITUDE));
                break;
            default:
                // replacedume "dd"
                // Decimal degrees
                lareplacedudeView.setText(resources.getString(R.string.gps_lareplacedude_value, location.getLareplacedude()));
                longitudeView.setText(resources.getString(R.string.gps_longitude_value, location.getLongitude()));
                break;
        }
        fixTime = location.getTime();
        if (location.hasAlreplacedude()) {
            if (prefDistanceUnits.equalsIgnoreCase(METERS)) {
                alreplacedudeView.setText(resources.getString(R.string.gps_alreplacedude_value_meters, location.getAlreplacedude()));
            } else {
                // Feet
                alreplacedudeView.setText(resources.getString(R.string.gps_alreplacedude_value_feet, UIUtils.toFeet(location.getAlreplacedude())));
            }
        } else {
            alreplacedudeView.setText("");
        }
        if (location.hreplacedpeed()) {
            if (prefSpeedUnits.equalsIgnoreCase(METERS_PER_SECOND)) {
                speedView.setText(resources.getString(R.string.gps_speed_value_meters_sec, location.getSpeed()));
            } else if (prefSpeedUnits.equalsIgnoreCase(KILOMETERS_PER_HOUR)) {
                speedView.setText(resources.getString(R.string.gps_speed_value_kilometers_hour, UIUtils.toKilometersPerHour(location.getSpeed())));
            } else {
                // Miles per hour
                speedView.setText(resources.getString(R.string.gps_speed_value_miles_hour, UIUtils.toMilesPerHour(location.getSpeed())));
            }
        } else {
            speedView.setText("");
        }
        if (location.hasBearing()) {
            bearingView.setText(resources.getString(R.string.gps_bearing_value, location.getBearing()));
        } else {
            bearingView.setText("");
        }
        updateLocationAccuracies(location);
        updateSpeedAndBearingAccuracies(location);
        updateFixTime();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    private void setStarted(boolean navigating) {
        if (navigating != this.navigating) {
            if (!navigating) {
                lareplacedudeView.setText(EMPTY_LAT_LONG);
                longitudeView.setText(EMPTY_LAT_LONG);
                fixTime = 0;
                updateFixTime();
                ttffView.setText("");
                alreplacedudeView.setText("");
                alreplacedudeMslView.setText("");
                horVertAccuracyView.setText("");
                speedView.setText("");
                speedAccuracyView.setText("");
                bearingView.setText("");
                bearingAccuracyView.setText("");
                numSats.setText("");
                pdopView.setText("");
                hvdopView.setText("");
                svCount = 0;
                gnssStatus.clear();
                sbreplacedtatus.clear();
                gnssAdapter.notifyDataSetChanged();
                sbasAdapter.notifyDataSetChanged();
            }
            this.navigating = navigating;
        }
    }

    private void updateFixTime() {
        fixTimeView.setText(fixTime == 0 ? "" : dateFormat.format(fixTime));
    }

    /**
     * Update views for horizontal and vertical location accuracies based on the provided location
     *
     * @param location The location to pull the accuracy from.
     */
    private void updateLocationAccuracies(Location location) {
        if (GpsTestUtil.isVerticalAccuracySupported(location)) {
            horVertAccuracyLabelView.setText(R.string.gps_hor_and_vert_accuracy_label);
            if (prefDistanceUnits.equalsIgnoreCase(METERS)) {
                horVertAccuracyView.setText(resources.getString(R.string.gps_hor_and_vert_accuracy_value_meters, location.getAccuracy(), location.getVerticalAccuracyMeters()));
            } else {
                // Feet
                horVertAccuracyView.setText(resources.getString(R.string.gps_hor_and_vert_accuracy_value_feet, UIUtils.toFeet(location.getAccuracy()), UIUtils.toFeet(location.getVerticalAccuracyMeters())));
            }
        } else {
            if (location.hasAccuracy()) {
                if (prefDistanceUnits.equalsIgnoreCase(METERS)) {
                    horVertAccuracyView.setText(resources.getString(R.string.gps_accuracy_value_meters, location.getAccuracy()));
                } else {
                    // Feet
                    horVertAccuracyView.setText(resources.getString(R.string.gps_accuracy_value_feet, UIUtils.toFeet(location.getAccuracy())));
                }
            } else {
                horVertAccuracyView.setText("");
            }
        }
    }

    /**
     * Update views for speed and bearing location accuracies based on the provided location
     *
     * @param location The location to pull the speed and bearing from.
     */
    private void updateSpeedAndBearingAccuracies(Location location) {
        if (GpsTestUtil.isSpeedAndBearingAccuracySupported()) {
            speedBearingAccuracyRow.setVisibility(View.VISIBLE);
            if (location.hreplacedpeedAccuracy()) {
                if (prefSpeedUnits.equalsIgnoreCase(METERS_PER_SECOND)) {
                    speedAccuracyView.setText(resources.getString(R.string.gps_speed_acc_value_meters_sec, location.getSpeedAccuracyMetersPerSecond()));
                } else if (prefSpeedUnits.equalsIgnoreCase(KILOMETERS_PER_HOUR)) {
                    speedAccuracyView.setText(resources.getString(R.string.gps_speed_acc_value_km_hour, UIUtils.toKilometersPerHour(location.getSpeedAccuracyMetersPerSecond())));
                } else {
                    // Miles per hour
                    speedAccuracyView.setText(resources.getString(R.string.gps_speed_acc_value_miles_hour, UIUtils.toMilesPerHour(location.getSpeedAccuracyMetersPerSecond())));
                }
            } else {
                speedAccuracyView.setText("");
            }
            if (location.hasBearingAccuracy()) {
                bearingAccuracyView.setText(resources.getString(R.string.gps_bearing_acc_value, location.getBearingAccuracyDegrees()));
            } else {
                bearingAccuracyView.setText("");
            }
        } else {
            speedBearingAccuracyRow.setVisibility(View.GONE);
        }
    }

    private void showDopViews() {
        pdopLabelView.setVisibility(View.VISIBLE);
        pdopView.setVisibility(View.VISIBLE);
        hvdopLabelView.setVisibility(View.VISIBLE);
        hvdopView.setVisibility(View.VISIBLE);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void updateGnssStatus(GnssStatus status) {
        setStarted(true);
        updateFixTime();
        if (!UIUtils.isFragmentAttached(this)) {
            // Fragment isn't visible, so return to avoid IllegalStateException (see #85)
            return;
        }
        snrCn0replacedle = resources.getString(R.string.gps_cn0_column_label);
        final int length = status.getSatelliteCount();
        svCount = 0;
        int usedInFixCount = 0;
        gnssStatus.clear();
        sbreplacedtatus.clear();
        while (svCount < length) {
            SatelliteStatus satStatus = new SatelliteStatus(status.getSvid(svCount), GpsTestUtil.getGnssConstellationType(status.getConstellationType(svCount)), status.getCn0DbHz(svCount), status.hasAlmanacData(svCount), status.hasEphemerisData(svCount), status.usedInFix(svCount), status.getElevationDegrees(svCount), status.getAzimuthDegrees(svCount));
            if (GpsTestUtil.isGnssCarrierFrequenciesSupported()) {
                if (status.hasCarrierFrequencyHz(svCount)) {
                    satStatus.setHasCarrierFrequency(true);
                    satStatus.setCarrierFrequencyHz(status.getCarrierFrequencyHz(svCount));
                }
            }
            if (satStatus.getGnssType() == GnssType.SBAS) {
                satStatus.setSbasType(GpsTestUtil.getSbasConstellationType(satStatus.getSvid()));
                sbreplacedtatus.add(satStatus);
            } else {
                gnssStatus.add(satStatus);
            }
            if (satStatus.getUsedInFix()) {
                usedInFixCount++;
            }
            svCount++;
        }
        numSats.setText(resources.getString(R.string.gps_num_sats_value, usedInFixCount, svCount));
        refreshViews();
    }

    private void refreshViews() {
        sortLists();
        updateListVisibility();
        gnssAdapter.notifyDataSetChanged();
        sbasAdapter.notifyDataSetChanged();
    }

    private void sortLists() {
        final int sortBy = PreferenceUtils.getSatSortOrderFromPreferences();
        // Below switch statement order must match arrays.xml sort_sats order
        switch(sortBy) {
            case 0:
                // Sort by Constellation
                gnssStatus = SortUtil.Companion.sortByGnssThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortBySbasThenId(sbreplacedtatus);
                break;
            case 1:
                // Sort by Carrier Frequency
                gnssStatus = SortUtil.Companion.sortByCarrierFrequencyThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortByCarrierFrequencyThenId(sbreplacedtatus);
                break;
            case 2:
                // Sort by Signal Strength
                gnssStatus = SortUtil.Companion.sortByCn0(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortByCn0(sbreplacedtatus);
                break;
            case 3:
                // Sort by Used in Fix
                gnssStatus = SortUtil.Companion.sortByUsedThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortByUsedThenId(sbreplacedtatus);
                break;
            case 4:
                // Sort by Constellation, Carrier Frequency
                gnssStatus = SortUtil.Companion.sortByGnssThenCarrierFrequencyThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortBySbasThenCarrierFrequencyThenId(sbreplacedtatus);
                break;
            case 5:
                // Sort by Constellation, Signal Strength
                gnssStatus = SortUtil.Companion.sortByGnssThenCn0ThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortBySbasThenCn0ThenId(sbreplacedtatus);
                break;
            case 6:
                // Sort by Constellation, Used in Fix
                gnssStatus = SortUtil.Companion.sortByGnssThenUsedThenId(gnssStatus);
                sbreplacedtatus = SortUtil.Companion.sortBySbasThenUsedThenId(sbreplacedtatus);
                break;
        }
    }

    private void setupUnitPreferences() {
        SharedPreferences settings = Application.getPrefs();
        Application app = Application.get();
        prefDistanceUnits = settings.getString(app.getString(R.string.pref_key_preferred_distance_units_v2), METERS);
        prefSpeedUnits = settings.getString(app.getString(R.string.pref_key_preferred_speed_units_v2), METERS_PER_SECOND);
    }

    /**
     * Sets the visibility of the lists
     */
    private void updateListVisibility() {
        if (!gnssStatus.isEmpty()) {
            gnssNotAvailableView.setVisibility(View.GONE);
            gnssStatusList.setVisibility(View.VISIBLE);
        } else {
            gnssNotAvailableView.setVisibility(View.VISIBLE);
            gnssStatusList.setVisibility(View.GONE);
        }
        if (!sbreplacedtatus.isEmpty()) {
            sbasNotAvailableView.setVisibility(View.GONE);
            sbreplacedtatusList.setVisibility(View.VISIBLE);
        } else {
            sbasNotAvailableView.setVisibility(View.VISIBLE);
            sbreplacedtatusList.setVisibility(View.GONE);
        }
    }

    /**
     * Show the Sort Dialog so the user can pick how they want to sort the list of satellites.
     */
    private void showSortByDialog() {
        final FragmentActivity activity = getActivity();
        if (activity == null) {
            Timber.wtf("The Activity is null so we are unable to show the sorting dialog.");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setreplacedle(R.string.menu_option_sort_by);
        final int currentSatOrder = PreferenceUtils.getSatSortOrderFromPreferences();
        builder.setSingleChoiceItems(R.array.sort_sats, currentSatOrder, (dialog, index) -> {
            setSortByClause(index);
            dialog.dismiss();
        });
        AlertDialog dialog = builder.create();
        dialog.setOwnerActivity(activity);
        dialog.show();
    }

    /**
     * Saves the "sort by" order to preferences
     *
     * @param index the index of R.array.sort_sats that should be set
     */
    private void setSortByClause(int index) {
        final String[] sortOptions = getResources().getStringArray(R.array.sort_sats);
        PreferenceUtils.saveString(getResources().getString(R.string.pref_key_default_sat_sort), sortOptions[index]);
    }

    private clreplaced SatelliteStatusAdapter extends RecyclerView.Adapter<SatelliteStatusAdapter.ViewHolder> {

        ConstellationType mConstellationType;

        SatelliteStatusAdapter(ConstellationType constellationType) {
            mConstellationType = constellationType;
        }

        @SuppressWarnings("WeakerAccess")
        clreplaced ViewHolder extends RecyclerView.ViewHolder {

            private final TextView svId;

            private final TextView gnssFlagHeader;

            private final ImageView gnssFlag;

            private final LinearLayout gnssFlagLayout;

            private final TextView carrierFrequency;

            private final TextView signal;

            private final TextView elevation;

            private final TextView azimuth;

            private final TextView statusFlags;

            ViewHolder(View v) {
                super(v);
                svId = v.findViewById(R.id.sv_id);
                gnssFlagHeader = v.findViewById(R.id.gnss_flag_header);
                gnssFlag = v.findViewById(R.id.gnss_flag);
                gnssFlagLayout = v.findViewById(R.id.gnss_flag_layout);
                carrierFrequency = v.findViewById(R.id.carrier_frequency);
                signal = v.findViewById(R.id.signal);
                elevation = v.findViewById(R.id.elevation);
                azimuth = v.findViewById(R.id.azimuth);
                statusFlags = v.findViewById(R.id.status_flags);
            }

            public TextView getSvId() {
                return svId;
            }

            public TextView getFlagHeader() {
                return gnssFlagHeader;
            }

            public ImageView getFlag() {
                return gnssFlag;
            }

            public LinearLayout getFlagLayout() {
                return gnssFlagLayout;
            }

            public TextView getCarrierFrequency() {
                return carrierFrequency;
            }

            public TextView getSignal() {
                return signal;
            }

            public TextView getElevation() {
                return elevation;
            }

            public TextView getAzimuth() {
                return azimuth;
            }

            public TextView getStatusFlags() {
                return statusFlags;
            }
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.status_row_item, viewGroup, false);
            return new ViewHolder(v);
        }

        @Override
        public int gereplacedemCount() {
            // Add 1 for header row
            if (mConstellationType == GNSS) {
                return gnssStatus.size() + 1;
            } else {
                return sbreplacedtatus.size() + 1;
            }
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder v, final int position) {
            if (position == 0) {
                // Show the header field for the GNSS flag and hide the ImageView
                v.getFlagHeader().setVisibility(View.VISIBLE);
                v.getFlag().setVisibility(View.GONE);
                v.getFlagLayout().setVisibility(View.GONE);
                // Populate the header fields
                v.getSvId().setText(resources.getString(R.string.gps_prn_column_label));
                v.getSvId().setTypeface(v.getSvId().getTypeface(), Typeface.BOLD);
                if (mConstellationType == GNSS) {
                    v.getFlagHeader().setText(resources.getString(R.string.gnss_flag_image_label));
                } else {
                    v.getFlagHeader().setText(resources.getString(R.string.sbas_flag_image_label));
                }
                if (GpsTestUtil.isGnssCarrierFrequenciesSupported()) {
                    v.getCarrierFrequency().setVisibility(View.VISIBLE);
                    v.getCarrierFrequency().setText(resources.getString(R.string.gps_carrier_column_label));
                    v.getCarrierFrequency().setTypeface(v.getCarrierFrequency().getTypeface(), Typeface.BOLD);
                } else {
                    v.getCarrierFrequency().setVisibility(View.GONE);
                }
                v.getSignal().setText(snrCn0replacedle);
                v.getSignal().setTypeface(v.getSignal().getTypeface(), Typeface.BOLD);
                v.getElevation().setText(resources.getString(R.string.gps_elevation_column_label));
                v.getElevation().setTypeface(v.getElevation().getTypeface(), Typeface.BOLD);
                v.getAzimuth().setText(resources.getString(R.string.gps_azimuth_column_label));
                v.getAzimuth().setTypeface(v.getAzimuth().getTypeface(), Typeface.BOLD);
                v.getStatusFlags().setText(resources.getString(R.string.gps_flags_column_label));
                v.getStatusFlags().setTypeface(v.getStatusFlags().getTypeface(), Typeface.BOLD);
            } else {
                // There is a header at 0, so the first data row will be at position - 1, etc.
                int dataRow = position - 1;
                List<SatelliteStatus> sats;
                if (mConstellationType == GNSS) {
                    sats = gnssStatus;
                } else {
                    sats = sbreplacedtatus;
                }
                // Show the row field for the GNSS flag mImage and hide the header
                v.getFlagHeader().setVisibility(View.GONE);
                v.getFlag().setVisibility(View.VISIBLE);
                v.getFlagLayout().setVisibility(View.VISIBLE);
                final Locale defaultLocale = Locale.getDefault();
                // Populate status data for this row
                v.getSvId().setText(String.format(defaultLocale, "%d", sats.get(dataRow).getSvid()));
                v.getFlag().setScaleType(ImageView.ScaleType.FIT_START);
                GnssType type = sats.get(dataRow).getGnssType();
                switch(type) {
                    case NAVSTAR:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagUsa);
                        break;
                    case GLONreplaced:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagRussia);
                        break;
                    case QZSS:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagreplacedan);
                        break;
                    case BEIDOU:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagChina);
                        break;
                    case GALILEO:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagEu);
                        break;
                    case IRNSS:
                        v.getFlag().setVisibility(View.VISIBLE);
                        v.getFlag().setImageDrawable(flagIndia);
                        break;
                    case SBAS:
                        setSbasFlag(sats.get(dataRow), v.getFlag());
                        break;
                    case UNKNOWN:
                        v.getFlag().setVisibility(View.INVISIBLE);
                        break;
                }
                if (GpsTestUtil.isGnssCarrierFrequenciesSupported()) {
                    if (sats.get(dataRow).getCarrierFrequencyHz() != SatelliteStatus.NO_DATA) {
                        // Convert Hz to MHz
                        float carrierMhz = MathUtils.toMhz(sats.get(dataRow).getCarrierFrequencyHz());
                        String carrierLabel = CarrierFreqUtils.getCarrierFrequencyLabel(sats.get(dataRow).getGnssType(), sats.get(dataRow).getSvid(), carrierMhz);
                        if (carrierLabel != null) {
                            // Make sure it's the normal text size (in case it's previously been
                            // resized to show raw number).  Use another TextView for default text size.
                            v.getCarrierFrequency().setTextSize(COMPLEX_UNIT_PX, v.getSvId().getTextSize());
                            // Show label such as "L1"
                            v.getCarrierFrequency().setText(carrierLabel);
                        } else {
                            // Shrink the size so we can show raw number
                            v.getCarrierFrequency().setTextSize(COMPLEX_UNIT_DIP, 10);
                            // Show raw number for carrier frequency
                            v.getCarrierFrequency().setText(String.format(defaultLocale, "%.3f", carrierMhz));
                        }
                    } else {
                        v.getCarrierFrequency().setText("");
                    }
                } else {
                    v.getCarrierFrequency().setVisibility(View.GONE);
                }
                if (sats.get(dataRow).getCn0DbHz() != SatelliteStatus.NO_DATA) {
                    v.getSignal().setText(String.format(defaultLocale, "%.1f", sats.get(dataRow).getCn0DbHz()));
                } else {
                    v.getSignal().setText("");
                }
                if (sats.get(dataRow).getElevationDegrees() != SatelliteStatus.NO_DATA) {
                    v.getElevation().setText(resources.getString(R.string.gps_elevation_column_value, sats.get(dataRow).getElevationDegrees()).replace(".0", "").replace(",0", ""));
                } else {
                    v.getElevation().setText("");
                }
                if (sats.get(dataRow).getAzimuthDegrees() != SatelliteStatus.NO_DATA) {
                    v.getAzimuth().setText(resources.getString(R.string.gps_azimuth_column_value, sats.get(dataRow).getAzimuthDegrees()).replace(".0", "").replace(",0", ""));
                } else {
                    v.getAzimuth().setText("");
                }
                char[] flags = new char[3];
                flags[0] = !sats.get(dataRow).getHasAlmanac() ? ' ' : 'A';
                flags[1] = !sats.get(dataRow).getHasEphemeris() ? ' ' : 'E';
                flags[2] = !sats.get(dataRow).getUsedInFix() ? ' ' : 'U';
                v.getStatusFlags().setText(new String(flags));
            }
        }

        private void setSbasFlag(SatelliteStatus status, ImageView flag) {
            switch(status.getSbasType()) {
                case WAAS:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagUsa);
                    break;
                case EGNOS:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagEu);
                    break;
                case GAGAN:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagIndia);
                    break;
                case MSAS:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagreplacedan);
                    break;
                case SDCM:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagRussia);
                    break;
                case SNAS:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagChina);
                    break;
                case SACCSA:
                    flag.setVisibility(View.VISIBLE);
                    flag.setImageDrawable(flagIcao);
                    break;
                case UNKNOWN:
                default:
                    flag.setVisibility(View.INVISIBLE);
            }
        }
    }
}

17 Source : TicTacToeActivity.java
with MIT License
from bridgefy

protected void disableInputs() {
    // disable play inputs
    for (int i = 0; i < mainBoard.getChildCount(); i++) {
        TableRow row = (TableRow) mainBoard.getChildAt(i);
        for (int j = 0; j < row.getChildCount(); j++) {
            TextView tv = (TextView) row.getChildAt(j);
            tv.setOnClickListener(null);
            tv.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.gray));
        }
    }
}

16 Source : HodinaView.java
with GNU General Public License v3.0
from vitSkalicky

private boolean addField(TableLayout layout, int resId, String fieldText) {
    if (fieldText != null && !fieldText.isEmpty()) {
        TableRow tr = (TableRow) LayoutInflater.from(getContext()).inflate(R.layout.lesson_details_dialog_row, null);
        TextView tw1 = tr.findViewById(R.id.textViewKey);
        TextView tw2 = tr.findViewById(R.id.textViewValue);
        tw1.setText(getContext().getString(resId));
        tw2.setText(fieldText);
        // tw2.setMaxLines(8000);
        // tr.addView(tw1);
        // tr.addView(tw2,new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        layout.addView(tr, new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        return true;
    } else {
        return false;
    }
}

16 Source : ThemeManager.java
with GNU General Public License v3.0
from vassela

public void setTableBorder(Context context, TableRow tableRow) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    int themeSet = Integer.parseInt(sharedPreferences.getString("preferences_theme_set", "0"));
    int colorThemeSet = Integer.parseInt(sharedPreferences.getString("preferences_color_theme_set", "7"));
    tableRow.setBackgroundResource(tablerow_drawable[themeSet][colorThemeSet]);
}

16 Source : AppearAnimationActivity.java
with Apache License 2.0
from Trumeet

private ArrayList<ArrayList<Object>> getAllChildren() {
    ArrayList<ArrayList<Object>> result = new ArrayList<>();
    result.add(new ArrayList<Object>(Collections.singletonList(icon_top)));
    List<TableRow> list = getRows(tableLayout);
    List<List<View>> radios = new ArrayList<>(list.size() * 5);
    for (TableRow row : list) {
        List<View> views = new ArrayList<>(row.getChildCount());
        for (int i = 0; i < row.getChildCount(); i++) {
            views.add(row.getChildAt(i));
        }
        radios.add(views);
    }
    for (int i = 0; i < radios.size(); i++) {
        ArrayList<Object> row = new ArrayList<>();
        row.addAll(radios.get(i));
        result.add(row);
    }
    return result;
}

16 Source : AppearAnimationActivity.java
with Apache License 2.0
from Trumeet

private static List<TableRow> getRows(TableLayout table) {
    List<TableRow> list = new ArrayList<>(table.getChildCount());
    for (int i = 0, j = table.getChildCount(); i < j; i++) {
        View view = table.getChildAt(i);
        if (view instanceof TableRow) {
            TableRow row = (TableRow) view;
            list.add(row);
        }
    }
    return list;
}

16 Source : ManualGames.java
with GNU General Public License v3.0
from TobiasBielefeld

@Override
public void onClick(View v) {
    // get index of the button as seen from the container
    TableRow row = (TableRow) v.getParent();
    TableLayout table = (TableLayout) row.getParent();
    int index = table.indexOfChild(row) * COLUMNS + row.indexOfChild(v);
    loadGameText(index);
}

16 Source : ZhanZhanQueryFragment.java
with Apache License 2.0
from SShineTeam

public clreplaced ZhanZhanQueryFragment extends SherlockFragment implements OnClickListener {

    public static final String EXTRA_MODE = "extraMode";

    private QueryLeftNewOptionInfo mQLNOInfo;

    private Button btnQueryType, btnFrom, btnTo, btnDepartureDate, btnReturnDate, btnTicketType, btnQuery;

    private TextView tvFromTip, tvToTip;

    private TableRow trReturnDate;

    private Button btnFromTimeRange, btnToTimeRange, btnTrainType;

    private ImageView ivSwap;

    private boolean[] mSelectedTrainTypes;

    private TrainHelper mTHelper = new TrainHelper();

    public static ZhanZhanQueryFragment getInstance(QueryLeftNewOptionInfo qlnoInfo) {
        ZhanZhanQueryFragment f1 = new ZhanZhanQueryFragment();
        f1.mQLNOInfo = qlnoInfo;
        return f1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_zhanzhan_query, container, false);
        // 查找控件并绑定单击事件
        btnQueryType = (Button) v.findViewById(R.id.zhanzhanQuery_btnQueryType);
        btnQueryType.setOnClickListener(this);
        tvFromTip = (TextView) v.findViewById(R.id.zhanzhanQuery_tvFromStationTip);
        tvFromTip.setOnClickListener(this);
        tvToTip = (TextView) v.findViewById(R.id.zhanzhanQuery_tvToStationTip);
        tvToTip.setOnClickListener(this);
        btnFrom = (Button) v.findViewById(R.id.zhanzhanQuery_btnStartStation);
        btnFrom.setOnClickListener(this);
        btnTo = (Button) v.findViewById(R.id.zhanzhanQuery_btnEndStation);
        btnTo.setOnClickListener(this);
        ivSwap = (ImageView) v.findViewById(R.id.zhanzhanQuery_ivSwap);
        ivSwap.setOnClickListener(this);
        btnDepartureDate = (Button) v.findViewById(R.id.zhanzhanQuery_btnDepartureDate);
        btnDepartureDate.setOnClickListener(this);
        trReturnDate = (TableRow) v.findViewById(R.id.zhanzhanQuery_trReturnDate);
        btnReturnDate = (Button) v.findViewById(R.id.zhanzhanQuery_btnReturnDate);
        btnReturnDate.setOnClickListener(this);
        btnTicketType = (Button) v.findViewById(R.id.zhanzhanQuery_btnTicketType);
        btnTicketType.setOnClickListener(this);
        btnFromTimeRange = (Button) v.findViewById(R.id.zhanzhanQuery_btnFromTimeRange);
        btnFromTimeRange.setOnClickListener(this);
        btnToTimeRange = (Button) v.findViewById(R.id.zhanzhanQuery_btnToTimeRange);
        btnToTimeRange.setOnClickListener(this);
        btnTrainType = (Button) v.findViewById(R.id.zhanzhanQuery_btnTrainType);
        btnTrainType.setOnClickListener(this);
        btnQuery = (Button) v.findViewById(R.id.zhanzhanQuery_btnQuery);
        btnQuery.setOnClickListener(this);
        if (mQLNOInfo == null) {
            mQLNOInfo = (QueryLeftNewOptionInfo) PersistentUtil.readObject(MyApp.getInstance().getPathBaseRoot(StoreValue.QUERY_OPTION_INFO_FILE));
        }
        if (mQLNOInfo == null) {
            // 给予默认值
            mQLNOInfo = new QueryLeftNewOptionInfo();
        }
        btnQueryType.setEnabled(false);
        btnFrom.setText(mQLNOInfo.getFrom_station_name());
        btnFrom.setTag(mQLNOInfo.getFrom_station_telecode());
        btnTo.setText(mQLNOInfo.getTo_station_name());
        btnTo.setTag(mQLNOInfo.getTo_station_telecode());
        btnQueryType.setText(TT.QUERY_TYPE_KEYS[0]);
        btnQueryType.setTag(TT.QUERY_TYPE_VALUES[0]);
        btnTicketType.setText(TT.QUERY_TICKET_TYPE_KEYS[0]);
        btnTicketType.setTag(TT.QUERY_TICKET_TYPE_VALUES[0]);
        btnFromTimeRange.setText(TT.TIME_RANGE_KEYS[0]);
        btnFromTimeRange.setTag(TT.TIME_RANGE_VALUES[0]);
        btnToTimeRange.setText(TT.TIME_RANGE_KEYS[0]);
        btnToTimeRange.setTag(TT.TIME_RANGE_VALUES[0]);
        mSelectedTrainTypes = new boolean[mTHelper.getTrainTypes().size()];
        for (int i = 0; i < mSelectedTrainTypes.length; i++) {
            mSelectedTrainTypes[i] = true;
        }
        setTrainTypeTextAndTag();
        // 取得当前日期
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.add(Calendar.DAY_OF_MONTH, 1);
        setDepartureDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        // 默认为单程查询
        trReturnDate.setVisibility(View.GONE);
        MyUtils.setToogleTextViewStatus(tvFromTip, mQLNOInfo.isFromExactMatch(), "出发站:");
        MyUtils.setToogleTextViewStatus(tvToTip, mQLNOInfo.isToExactMatch(), "目的站:");
        this.setHasOptionsMenu(true);
        if (!A6Util.isCanBookingStuTicket(System.currentTimeMillis())) {
            btnTicketType.setEnabled(false);
        }
        handleResignMode();
        return v;
    }

    /**
     * 处理改签模式
     */
    private void handleResignMode() {
        if (mQLNOInfo == null) {
            return;
        }
        if (mQLNOInfo.getMode() == QueryLeftNewOptionInfo.MODE_RESIGN) {
            btnQueryType.setText(TT.QUERY_TYPE_KEYS[0]);
            btnQueryType.setTag(TT.QUERY_TYPE_VALUES[0]);
            btnQueryType.setEnabled(false);
            btnFrom.setEnabled(false);
            btnTo.setEnabled(false);
        }
    }

    private boolean setTrainTypeTextAndTag() {
        String strText = "";
        int tempCount = 0;
        for (int i = 0; i < mSelectedTrainTypes.length; i++) {
            if (mSelectedTrainTypes[i]) {
                tempCount++;
                strText += mTHelper.getTrainNames().valueAt(i) + ",";
            }
        }
        if (tempCount == 0) {
            btnTrainType.setText("请至少选一项");
            btnTrainType.setTag(null);
            return false;
        } else if (tempCount == mSelectedTrainTypes.length) {
            btnTrainType.setText("全部");
        } else {
            btnTrainType.setText(strText.substring(0, strText.length() - 1));
        }
        btnTrainType.setTag(mSelectedTrainTypes);
        return true;
    }

    private void setReturnDate(int year, int monthOfYear, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(year, monthOfYear, dayOfMonth);
        String strFormat = "yyyy年MM月dd日";
        SimpleDateFormat sdf = new SimpleDateFormat(strFormat, Locale.CHINA);
        btnReturnDate.setText(sdf.format(c.getTime()) + "  " + TimeUtil.getWeek(c.getTime()));
        btnReturnDate.setTag(c.getTimeInMillis() + "");
    }

    private void setDepartureDate(int year, int monthOfYear, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(year, monthOfYear, dayOfMonth);
        String strFormat = "yyyy年MM月dd日";
        SimpleDateFormat sdf = new SimpleDateFormat(strFormat, Locale.CHINA);
        btnDepartureDate.setText(sdf.format(c.getTime()) + "  " + TimeUtil.getWeek(c.getTime()));
        btnDepartureDate.setTag(c.getTimeInMillis() + "");
        setReturnDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case android.R.id.home:
                this.getSherlockActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        Intent intent1 = new Intent(this.getActivity(), SelectAty.clreplaced);
        // 不加此标志StationAty有时执行两次finish()才会返回。
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent1.putExtra(SelectAty.SEARCH_TYPE, SelectAty.SEARCH_STATION);
        switch(v.getId()) {
            case R.id.zhanzhanQuery_btnQueryType:
                FavoriteCharacterDialogFragment.show(this.getActivity(), TrainSchAty.REQUEST_QUERY_TYPE, "查询类别", TT.QUERY_TYPE_KEYS);
                break;
            case R.id.zhanzhanQuery_tvFromStationTip:
                boolean status = false;
                status = MyUtils.getToogleTextViewStatus(tvFromTip) == true ? false : true;
                mQLNOInfo.setFromExactMatch(status);
                MyUtils.setToogleTextViewStatus(tvFromTip, status, "出发站:");
                if (status) {
                    showMsg("已开启出发站精确匹配");
                } else {
                    showMsg("已关闭出发站精确匹配");
                }
                break;
            case R.id.zhanzhanQuery_tvToStationTip:
                boolean status1 = false;
                status1 = MyUtils.getToogleTextViewStatus(tvToTip) == true ? false : true;
                mQLNOInfo.setToExactMatch(status1);
                MyUtils.setToogleTextViewStatus(tvToTip, status1, "目的站:");
                if (status1) {
                    showMsg("已开启目的站精确匹配");
                } else {
                    showMsg("已关闭目的站精确匹配");
                }
                break;
            case R.id.zhanzhanQuery_btnStartStation:
                startActivityForResult(intent1, 1);
                break;
            case R.id.zhanzhanQuery_btnEndStation:
                startActivityForResult(intent1, 2);
                break;
            case R.id.zhanzhanQuery_ivSwap:
                // 旋转一圈
                ImageUtil.rotateImageOnce(getActivity(), ivSwap);
                CharSequence csTemp = "";
                Object obj;
                csTemp = btnFrom.getText();
                btnFrom.setText(btnTo.getText());
                btnTo.setText(csTemp);
                obj = btnFrom.getTag();
                btnFrom.setTag(btnTo.getTag());
                btnTo.setTag(obj);
                break;
            case R.id.zhanzhanQuery_btnDepartureDate:
                if (btnDepartureDate.getTag() instanceof String) {
                    try {
                        long milliseconds = Long.valueOf((String) btnDepartureDate.getTag());
                        Calendar c = Calendar.getInstance(Locale.CHINA);
                        c.setTimeInMillis(milliseconds);
                        new DatePickerDialog(this.getActivity(), new OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                setDepartureDate(year, monthOfYear, dayOfMonth);
                            }
                        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.zhanzhanQuery_btnReturnDate:
                if (btnReturnDate.getTag() instanceof String) {
                    try {
                        long returnMilliseconds = Long.valueOf((String) btnReturnDate.getTag());
                        Calendar returnCalendar = Calendar.getInstance(Locale.CHINA);
                        returnCalendar.setTimeInMillis(returnMilliseconds);
                        new DatePickerDialog(this.getActivity(), new OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                try {
                                    Calendar returnCalendar1 = Calendar.getInstance(Locale.CHINA);
                                    returnCalendar1.set(year, monthOfYear, dayOfMonth);
                                    if (btnDepartureDate.getTag() instanceof String) {
                                        long milliseconds = Long.valueOf((String) btnDepartureDate.getTag());
                                        Calendar c = Calendar.getInstance(Locale.CHINA);
                                        c.setTimeInMillis(milliseconds);
                                        if (returnCalendar1.getTimeInMillis() < c.getTimeInMillis()) {
                                            showMsg("返程日期不得小于出发日期哦" + SF.TIP);
                                        } else {
                                            setReturnDate(year, monthOfYear, dayOfMonth);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, returnCalendar.get(Calendar.YEAR), returnCalendar.get(Calendar.MONTH), returnCalendar.get(Calendar.DAY_OF_MONTH)).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.zhanzhanQuery_btnTicketType:
                FavoriteCharacterDialogFragment.show(this.getActivity(), TrainSchAty.REQUEST_TICKET_TYPE, "车票类别", TT.QUERY_TICKET_TYPE_KEYS);
                break;
            case R.id.zhanzhanQuery_btnFromTimeRange:
                FavoriteCharacterDialogFragment.show(getActivity(), TrainSchAty.REQUEST_FROM_TIME_RANGE, "发车时间", TT.TIME_RANGE_KEYS);
                break;
            case R.id.zhanzhanQuery_btnToTimeRange:
                FavoriteCharacterDialogFragment.show(getActivity(), TrainSchAty.REQUEST_TO_TIME_RANGE, "到达时间", TT.TIME_RANGE_KEYS);
                break;
            case R.id.zhanzhanQuery_btnTrainType:
                MultiChoiceFragment.show(getActivity(), TrainSchAty.REQUEST_TRAIN_TYPE, "车次类型", mTHelper.getTrainTypeNames(), mSelectedTrainTypes);
                break;
            case R.id.zhanzhanQuery_btnQuery:
                doQuery();
                break;
        }
    }

    private void saveOptionInfo() {
        mQLNOInfo.setFrom_station_name(btnFrom.getText().toString());
        mQLNOInfo.setFrom_station_telecode(btnFrom.getTag() == null ? null : btnFrom.getTag().toString());
        mQLNOInfo.setTo_station_name(btnTo.getText().toString());
        mQLNOInfo.setTo_station_telecode(btnTo.getTag() == null ? null : btnTo.getTag().toString());
        PersistentUtil.writeObject(mQLNOInfo, MyApp.getInstance().getPathBaseRoot(StoreValue.QUERY_OPTION_INFO_FILE));
    }

    private void doQuery() {
        if (btnFrom.getText().toString().equals("")) {
            showMsg("请选择出发站点" + SF.TIP);
            return;
        }
        if (btnTo.getText().toString().equals("")) {
            showMsg("请选择目的站点" + SF.TIP);
            return;
        }
        if (btnDepartureDate.getTag() == null || btnDepartureDate.getTag().toString().equals("")) {
            showMsg("请选择出发日" + SF.TIP);
            return;
        }
        if (trReturnDate.getVisibility() == View.VISIBLE && (btnReturnDate.getTag() == null)) {
            showMsg("请选择返程日" + SF.TIP);
            return;
        }
        Date departureDate = null, returnDate = null;
        if (btnDepartureDate.getTag() instanceof String) {
            try {
                long milliseconds = Long.valueOf((String) btnDepartureDate.getTag());
                Calendar c = Calendar.getInstance(Locale.CHINA);
                c.setTimeInMillis(milliseconds);
                departureDate = c.getTime();
                if (btnReturnDate.getTag() instanceof String) {
                    long returnMilliseconds = Long.valueOf((String) btnReturnDate.getTag());
                    Calendar returnCalendar = Calendar.getInstance(Locale.CHINA);
                    returnCalendar.setTimeInMillis(returnMilliseconds);
                    returnDate = returnCalendar.getTime();
                    if (trReturnDate.getVisibility() == View.VISIBLE) {
                        if (returnCalendar.getTimeInMillis() < c.getTimeInMillis()) {
                            showMsg("返程日期不得小于出发日期哦" + SF.TIP);
                            return;
                        }
                        ;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (departureDate == null || returnDate == null) {
            showMsg("日期有误");
            return;
        }
        setTrainTypeTextAndTag();
        if (btnTrainType.getTag() == null) {
            showMsg("车次类型请至少选择一项" + SF.FAIL);
            return;
        }
        saveOptionInfo();
        QueryLeftNewOptionInfo qlndInfo = new QueryLeftNewOptionInfo();
        qlndInfo.setFrom_station_telecode(btnFrom.getTag().toString());
        qlndInfo.setTo_station_telecode(btnTo.getTag().toString());
        qlndInfo.setFrom_station_name(btnFrom.getText().toString());
        qlndInfo.setTo_station_name(btnTo.getText().toString());
        qlndInfo.setFromExactMatch(MyUtils.getToogleTextViewStatus(tvFromTip));
        qlndInfo.setToExactMatch(MyUtils.getToogleTextViewStatus(tvToTip));
        qlndInfo.setDeparture_time(TimeUtil.getDFormat().format(departureDate.getTime()));
        if (trReturnDate.getVisibility() == View.VISIBLE) {
            qlndInfo.setReturn_time(TimeUtil.getDFormat().format(returnDate.getTime()));
            qlndInfo.setDay_difference(TimeUtil.getIntervalDays(departureDate, returnDate));
        } else {
            qlndInfo.setReturn_time(null);
            qlndInfo.setDay_difference(0);
        }
        if (qlndInfo.getMode() == QueryLeftNewOptionInfo.MODE_NORMAL) {
            qlndInfo.setTour_flag(mQLNOInfo.getReturn_time() == null ? TT.getTour_flags().get("dc") : TT.getTour_flags().get("wc"));
        } else {
            qlndInfo.setTour_flag(TT.getTour_flags().get("gc"));
        }
        qlndInfo.setTicket_type(btnTicketType.getTag().toString());
        qlndInfo.setFrom_time_range(btnFromTimeRange.getTag().toString());
        qlndInfo.setTo_time_range(btnToTimeRange.getTag().toString());
        qlndInfo.setSelectedTrainTypeIndexes((boolean[]) btnTrainType.getTag());
        Intent intent = new Intent(this.getSherlockActivity(), TrainSchListAty.clreplaced);
        intent.putExtra(TrainSchListAty.EXTRA_OPTION_INFO, qlndInfo);
        this.getActivity().startActivity(intent);
    }

    private void showMsg(String strMsg) {
        Toast.makeText(this.getActivity(), strMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        if (resultCode == Activity.RESULT_OK) {
            switch(requestCode) {
                case 1:
                    btnFrom.setText(data.getExtras().getString(SelectAty.RESULT_KEY));
                    btnFrom.setTag(data.getExtras().getString(SelectAty.RESULT_VALUE));
                    saveOptionInfo();
                    break;
                case 2:
                    btnTo.setText(data.getExtras().getString(SelectAty.RESULT_KEY));
                    btnTo.setTag(data.getExtras().getString(SelectAty.RESULT_VALUE));
                    saveOptionInfo();
                    break;
            }
        }
    }

    public void onMultiChoiceSelectedFromActivity(View v, int requestCode, int which, boolean isChecked) {
        switch(requestCode) {
            case TrainSchAty.REQUEST_TRAIN_TYPE:
                if (mSelectedTrainTypes != null) {
                    mSelectedTrainTypes[which] = isChecked;
                }
                break;
        }
    }

    public void onMultiChoicePositiveButtonClickedFromActivity(int requestCode) {
        try {
            switch(requestCode) {
                case TrainSchAty.REQUEST_TRAIN_TYPE:
                    if (!setTrainTypeTextAndTag()) {
                        showMsg("请至少选择一项" + SF.FAIL);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onLisreplacedemSelectedFromActivity(int requestCode, String value, int number) {
        try {
            switch(requestCode) {
                case TrainSchAty.REQUEST_QUERY_TYPE:
                    btnQueryType.setText(TT.QUERY_TYPE_KEYS[number]);
                    btnQueryType.setTag(TT.QUERY_TYPE_VALUES[number]);
                    if (number == 0) {
                        trReturnDate.setVisibility(View.GONE);
                    } else {
                        trReturnDate.setVisibility(View.VISIBLE);
                    }
                    break;
                case TrainSchAty.REQUEST_TICKET_TYPE:
                    btnTicketType.setText(TT.QUERY_TICKET_TYPE_KEYS[number]);
                    btnTicketType.setTag(TT.QUERY_TICKET_TYPE_VALUES[number]);
                    break;
                case TrainSchAty.REQUEST_FROM_TIME_RANGE:
                    btnFromTimeRange.setText(TT.TIME_RANGE_KEYS[number]);
                    btnFromTimeRange.setTag(TT.TIME_RANGE_VALUES[number]);
                    break;
                case TrainSchAty.REQUEST_TO_TIME_RANGE:
                    btnToTimeRange.setText(TT.TIME_RANGE_KEYS[number]);
                    btnToTimeRange.setTag(TT.TIME_RANGE_VALUES[number]);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

16 Source : MyFragment.java
with MIT License
from pandafa

public clreplaced MyFragment extends Fragment {

    private MyApplication myApplication;

    private TextView textViewName, textViewKind;

    private TableRow tablePreplacedwd, tableOrder, tableCollection, tableShoppingCar;

    private TableRow tableUpdate, tableAbout, tableYi, tableTel;

    private Button buttonLogOut, btnLogin, btnReg;

    private LinearLayout layoutLogout, layoutNoLogin, layoutLoged;

    private LayoutInflater inflater;

    public MyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.layoutLogout = layoutLogout;
        View v = inflater.inflate(R.layout.fragment_my, container, false);
        myApplication = (MyApplication) getActivity().getApplication();
        textViewName = (TextView) v.findViewById(R.id.textView_fmy_loginUserName);
        textViewKind = (TextView) v.findViewById(R.id.textView_fmy_kind);
        layoutLogout = (LinearLayout) v.findViewById(R.id.linearLayout_fmy_logout);
        layoutNoLogin = (LinearLayout) v.findViewById(R.id.linearLayout_fmy_noLogin);
        layoutLoged = (LinearLayout) v.findViewById(R.id.linearLayout_fmy_login);
        buttonLogOut = (Button) v.findViewById(R.id.button_fmy_logout);
        btnLogin = (Button) v.findViewById(R.id.button_fmy_login);
        btnReg = (Button) v.findViewById(R.id.button_fmy_reg);
        tablePreplacedwd = (TableRow) v.findViewById(R.id.table_fmy_change_preplacedwd);
        tableOrder = (TableRow) v.findViewById(R.id.table_fmy_order);
        tableCollection = (TableRow) v.findViewById(R.id.table_fmy_collect);
        tableShoppingCar = (TableRow) v.findViewById(R.id.table_fmy_shoppingCar);
        tableUpdate = (TableRow) v.findViewById(R.id.table_fmy_update);
        tableAbout = (TableRow) v.findViewById(R.id.table_fmy_about);
        tableYi = (TableRow) v.findViewById(R.id.table_fmy_yi);
        tableTel = (TableRow) v.findViewById(R.id.table_fmy_tel);
        // 到收藏夹
        tableCollection.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (myApplication.isB_login()) {
                    Intent intent = new Intent(getActivity(), CollectionActivity.clreplaced);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "请先登录!", Toast.LENGTH_LONG).show();
                }
            }
        });
        // 到忘记密码
        tablePreplacedwd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (myApplication.isB_login()) {
                    Intent intent = new Intent(getActivity(), ForgerActivity.clreplaced);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "请先登录!", Toast.LENGTH_LONG).show();
                }
            }
        });
        // 到我的订单
        tableOrder.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (myApplication.isB_login()) {
                    myApplication.getViewPager().setCurrenreplacedem(4);
                } else {
                    Toast.makeText(getContext(), "请先登录!", Toast.LENGTH_LONG).show();
                }
            }
        });
        // 到我的购物车
        tableShoppingCar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (myApplication.isB_login()) {
                    myApplication.getViewPager().setCurrenreplacedem(3);
                } else {
                    Toast.makeText(getContext(), "请先登录!", Toast.LENGTH_LONG).show();
                }
            }
        });
        // 到更新
        tableUpdate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "此版本为最新版,无需更新", Toast.LENGTH_LONG).show();
            }
        });
        // 到关于
        tableAbout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "作者:软件15001班 陈锡鑫", Toast.LENGTH_LONG).show();
            }
        });
        // 到意见
        tableYi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "本服务暂时关闭", Toast.LENGTH_LONG).show();
            }
        });
        // 到电话
        tableTel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setreplacedle("客服电话");
                // builder.setIcon(R.drawable.main_user);
                builder.setMessage("拨打13688888888");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String data = "tel:" + "13688888888";
                        Uri uri = Uri.parse(data);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(uri);
                        startActivity(intent);
                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
        // 登录按钮
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.clreplaced);
                startActivity(intent);
            }
        });
        // 注册按钮
        btnReg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RegisterActivity.clreplaced);
                startActivity(intent);
            }
        });
        // 退出按钮
        buttonLogOut.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 执行退出操作
                myApplication.setB_login(false);
                myApplication.setS_loginUserId(null);
                myApplication.setS_loginUserKind(null);
                myApplication.setS_loginUserName(null);
                myApplication.setNumberShoppingCar(-1);
                myApplication.setNumberOrder(-1);
                myApplication.setSessionId(null);
                Toast.makeText(getContext(), "执行退出操作", Toast.LENGTH_SHORT).show();
                onResume();
            }
        });
        // 
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        myApplication = (MyApplication) getActivity().getApplication();
        // 如何显示
        layoutNoLogin.setVisibility(View.INVISIBLE);
        layoutLoged.setVisibility(View.INVISIBLE);
        layoutLogout.setVisibility(View.GONE);
        if (myApplication.isB_login()) {
            if (myApplication.getS_loginUserKind().equals("m")) {
                textViewKind.setText("管理员");
            } else {
                textViewKind.setText("普通用户");
            }
            textViewName.setText("【" + myApplication.getS_loginUserName() + "】");
            layoutLoged.setVisibility(View.VISIBLE);
            layoutLogout.setVisibility(View.VISIBLE);
        } else {
            layoutNoLogin.setVisibility(View.VISIBLE);
        }
    }
}

16 Source : TableLayout8.java
with Apache License 2.0
from jiyouliang

private void appendRow(TableLayout table) {
    TableRow row = new TableRow(this);
    TextView label = new TextView(this);
    label.setText(R.string.table_layout_8_quit);
    label.setPadding(3, 3, 3, 3);
    TextView shortcut = new TextView(this);
    shortcut.setText(R.string.table_layout_8_ctrlq);
    shortcut.setPadding(3, 3, 3, 3);
    shortcut.setGravity(Gravity.RIGHT | Gravity.TOP);
    row.addView(label, new TableRow.LayoutParams(1));
    row.addView(shortcut, new TableRow.LayoutParams());
    table.addView(row, new TableLayout.LayoutParams());
}

16 Source : TableLayout7.java
with Apache License 2.0
from jiyouliang

private void appendRow(TableLayout table) {
    TableRow row = new TableRow(this);
    TextView label = new TextView(this);
    label.setText(R.string.table_layout_7_quit);
    label.setPadding(3, 3, 3, 3);
    TextView shortcut = new TextView(this);
    shortcut.setText(R.string.table_layout_7_ctrlq);
    shortcut.setPadding(3, 3, 3, 3);
    shortcut.setGravity(Gravity.RIGHT | Gravity.TOP);
    row.addView(label, new TableRow.LayoutParams(1));
    row.addView(shortcut, new TableRow.LayoutParams());
    table.addView(row, new TableLayout.LayoutParams());
}

16 Source : TableBuilder.java
with Apache License 2.0
from iqiyi

public TableLayout build(Context context) {
    if (colCount == 0) {
        return layout;
    }
    itemPadding = (int) (context.getResources().getDisplayMetrics().density * 10);
    if (layout == null) {
        layout = new TableView(context);
    } else {
        layout.removeAllViews();
    }
    if (boarderStroke >= 0) {
        layout.setBoarderStrokeWidth(boarderStroke);
    }
    if (centerStroke >= 0) {
        layout.setCenterStrokeWidth(centerStroke);
    }
    boolean hasRowName = false;
    if (mStretchableColumns != null) {
        for (int i : mStretchableColumns) {
            layout.setColumnStretchable(i, true);
        }
    }
    // [update row count by row Names]
    if (rowNames != null && rowNames.length >= rowCount) {
        rowCount = rowNames.length;
        hasRowName = true;
        if (rowNameColor != 0) {
            layout.setRowNameColor(rowNameColor);
        }
    }
    // [update rowCount by row data]
    if (mData != null && mData.length > 0) {
        int dataLen = mData.length;
        int row = dataLen / colCount;
        if (row > rowCount) {
            rowCount = row;
        }
    }
    if (boarderColor != 0) {
        layout.setBoarderColor(boarderColor);
    }
    if (colNames != null && colNames.length >= colCount) {
        colCount = colNames.length;
        // [add col Name]
        TableRow tableRow = new TableRow(context);
        if (hasRowName) {
            // [empty]
            tableRow.addView(new TextView(context));
        }
        // [-1 row stands for col names]
        inflateRowData(tableRow, colNames, 0, -1);
        layout.addView(tableRow);
        if (colNameColor != 0) {
            tableRow.setBackgroundColor(colNameColor);
        }
    }
    if (rowCount > 0) {
        int p = 0;
        while (p < rowCount) {
            TableRow row = new TableRow(context);
            if (hasRowName) {
                View itemView = createRowNameView(context, row, p, rowNames[p]);
                row.addView(itemView);
            }
            inflateRowData(row, mData, p * colCount, p);
            layout.addView(row);
            p++;
        }
    }
    return layout;
}

16 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

public clreplaced FilterConfig implements OnClickListener, DialogInterface.OnKeyListener {

    static String NEW_ITEM = "<new>";

    static String INVALID_URL = "<invalid URL!>";

    static String ALL_CATEGORIES = "All categories";

    static String ALL_ACTIVE = "All active filters";

    TableLayout configTable;

    FilterConfigEntry[] filterEntries;

    boolean loaded = false;

    TableRow editedRow;

    Button editOk;

    Button editDelete;

    Button editCancel;

    Dialog editDialog;

    Button categoryUp;

    Button categoryDown;

    TextView categoryField;

    TreeMap<String, Integer> categoryMap;

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)
            dialog.dismiss();
        return false;
    }

    public static clreplaced FilterConfigEntry {

        boolean active;

        String category;

        String id;

        String url;

        public FilterConfigEntry(boolean active, String category, String id, String url) {
            this.active = active;
            this.category = category;
            this.id = id;
            this.url = url;
        }
    }

    public FilterConfig(TableLayout table, Button categoryUp, Button categoryDn, TextView categoryField) {
        configTable = table;
        editDialog = new Dialog(table.getContext(), R.style.Theme_dialog_replacedleBar);
        editDialog.setOnKeyListener(this);
        editDialog.setContentView(R.layout.filterentryeditdialog);
        editDialog.setreplacedle(table.getContext().getResources().getString(R.string.editFilterDialogreplacedle));
        editOk = editDialog.findViewById(R.id.filterEditOkBtn);
        editDelete = editDialog.findViewById(R.id.filterEditDelBtn);
        editCancel = editDialog.findViewById(R.id.filterEditCancelBtn);
        editOk.setOnClickListener(this);
        editDelete.setOnClickListener(this);
        editCancel.setOnClickListener(this);
        this.categoryUp = categoryUp;
        this.categoryDown = categoryDn;
        this.categoryField = categoryField;
        categoryField.setText(ALL_ACTIVE);
        categoryMap = new TreeMap();
    }

    private View[] getContentCells(TableRow row) {
        View[] result = new View[5];
        for (int i = 0; i < 5; i++) result[i] = row.getChildAt(i);
        // element 1 is a scrollview with nested TextView
        result[2] = ((ViewGroup) result[2]).getChildAt(0);
        // element 2 is a scrollview with nested TextView
        result[3] = ((ViewGroup) result[3]).getChildAt(0);
        return result;
    }

    private void addItem(FilterConfigEntry entry) {
        TableRow row = (TableRow) LayoutInflater.from(configTable.getContext()).inflate(R.layout.filterconfigentry, null);
        configTable.addView(row);
        View[] cells = getContentCells(row);
        ((CheckBox) cells[0]).setChecked(entry.active);
        ((TextView) cells[1]).setText(entry.category);
        ((TextView) cells[2]).setText(entry.id);
        ((TextView) cells[3]).setText(entry.url);
        cells[4].setOnClickListener(this);
        setVisibility(row);
    }

    private void setVisibility(TableRow row) {
        String currentCategory = categoryField.getText().toString();
        String rowCategory = ((TextView) row.getVirtualChildAt(1)).getText().toString();
        boolean active = ((CheckBox) row.getVirtualChildAt(0)).isChecked();
        boolean visible = (currentCategory.equals(ALL_CATEGORIES)) || (currentCategory.equals(ALL_ACTIVE) && active) || (rowCategory.equals(NEW_ITEM)) || (rowCategory.equals(currentCategory));
        if (visible)
            row.setVisibility(View.VISIBLE);
        else
            row.setVisibility(View.GONE);
    }

    public void setEntries(FilterConfigEntry[] entries) {
        this.filterEntries = entries;
        categoryMap.clear();
        categoryMap.put(ALL_ACTIVE, new Integer(0));
        categoryMap.put(ALL_CATEGORIES, new Integer(0));
        for (int i = 0; i < filterEntries.length; i++) {
            Integer count = categoryMap.get(filterEntries[i].category);
            if (count == null)
                count = new Integer(0);
            count = new Integer(count.intValue() + 1);
            categoryMap.put(filterEntries[i].category, count);
        }
    }

    public void load() {
        if (loaded)
            return;
        for (int i = 0; i < filterEntries.length; i++) addItem(filterEntries[i]);
        addEmptyEndItem();
        categoryDown.setOnClickListener(this);
        categoryUp.setOnClickListener(this);
        loaded = true;
    }

    private void addEmptyEndItem() {
        addItem(new FilterConfigEntry(false, NEW_ITEM, NEW_ITEM, NEW_ITEM));
    }

    public String getCurrentCategory() {
        return categoryField.getText().toString();
    }

    public void setCurrentCategory(String category) {
        categoryField.setText(category);
    }

    public FilterConfigEntry[] getFilterEntries() {
        if (!loaded)
            return filterEntries;
        int count = configTable.getChildCount() - 2;
        FilterConfigEntry[] result = new FilterConfigEntry[count];
        for (int i = 0; i < count; i++) {
            View[] rowContent = getContentCells((TableRow) configTable.getChildAt(i + 1));
            result[i] = new FilterConfigEntry(((CheckBox) rowContent[0]).isChecked(), ((TextView) rowContent[1]).getText().toString().trim(), ((TextView) rowContent[2]).getText().toString().trim(), ((TextView) rowContent[3]).getText().toString().trim());
        }
        return result;
    }

    public void clear() {
        filterEntries = getFilterEntries();
        int count = configTable.getChildCount() - 1;
        for (int i = count; i > 0; i--) {
            TableRow row = (TableRow) configTable.getChildAt(i);
            row.getChildAt(4).setOnClickListener(null);
            configTable.removeView(row);
        }
        categoryDown.setOnClickListener(null);
        categoryUp.setOnClickListener(null);
        loaded = false;
    }

    @Override
    public void onClick(View v) {
        if (v == editOk || v == editDelete || v == editCancel)
            handleEditDialogEvent(v);
        else if (v == categoryUp || v == categoryDown)
            handleCategoryChange((Button) v);
        else
            showEditDialog((TableRow) v.getParent());
    }

    private void handleCategoryChange(Button v) {
        String currentCategory = categoryField.getText().toString();
        String newCategory;
        if (!categoryMap.containsKey(currentCategory))
            newCategory = ALL_ACTIVE;
        else if (v == categoryUp) {
            newCategory = categoryMap.higherKey(currentCategory);
            if (newCategory == null)
                newCategory = categoryMap.firstKey();
        } else {
            newCategory = categoryMap.lowerKey(currentCategory);
            if (newCategory == null)
                newCategory = categoryMap.lastKey();
        }
        categoryField.setText(newCategory);
        updateView();
    }

    private void updateView() {
        int count = configTable.getChildCount() - 2;
        for (int i = 0; i < count; i++) {
            TableRow row = ((TableRow) configTable.getChildAt(i + 1));
            setVisibility(row);
        }
    }

    private void showEditDialog(TableRow row) {
        editedRow = row;
        View[] currentContent = getContentCells(editedRow);
        ((CheckBox) editDialog.findViewById(R.id.activeChk)).setChecked(((CheckBox) currentContent[0]).isChecked());
        ((TextView) editDialog.findViewById(R.id.filterCategory)).setText(((TextView) currentContent[1]).getText().toString());
        ((TextView) editDialog.findViewById(R.id.filterName)).setText(((TextView) currentContent[2]).getText().toString());
        ((TextView) editDialog.findViewById(R.id.filterUrl)).setText(((TextView) currentContent[3]).getText().toString());
        editDialog.show();
        WindowManager.LayoutParams lp = editDialog.getWindow().getAttributes();
        lp.width = (int) (configTable.getContext().getResources().getDisplayMetrics().widthPixels * 1.00);
        ;
        editDialog.getWindow().setAttributes(lp);
    }

    private void handleEditDialogEvent(View v) {
        if (v == editCancel) {
            editDialog.dismiss();
            editDialog.findViewById(R.id.errorMsg).setVisibility(View.GONE);
            return;
        }
        View[] currentContent = getContentCells(editedRow);
        boolean newItem = ((TextView) currentContent[2]).getText().toString().equals(NEW_ITEM);
        if (v == editDelete) {
            if (!newItem) {
                editedRow.getChildAt(3).setOnClickListener(null);
                configTable.removeView(editedRow);
                String currentCategory = ((TextView) currentContent[1]).getText().toString();
                Integer count = categoryMap.get(currentCategory);
                if (count.intValue() == 1)
                    categoryMap.remove(currentCategory);
                else
                    categoryMap.put(currentCategory, new Integer(count.intValue() - 1));
            }
            editDialog.dismiss();
            editDialog.findViewById(R.id.errorMsg).setVisibility(View.GONE);
        } else if (v == editOk) {
            View[] content = new View[4];
            content[0] = editDialog.findViewById(R.id.activeChk);
            content[1] = editDialog.findViewById(R.id.filterCategory);
            content[2] = editDialog.findViewById(R.id.filterName);
            content[3] = editDialog.findViewById(R.id.filterUrl);
            try {
                validateContent(content);
            } catch (Exception e) {
                TextView errorView = editDialog.findViewById(R.id.errorMsg);
                errorView.setVisibility(View.VISIBLE);
                errorView.setText(e.getMessage());
                return;
            }
            boolean active = ((CheckBox) content[0]).isChecked();
            String category = ((TextView) content[1]).getText().toString();
            String name = ((TextView) content[2]).getText().toString();
            String url = ((TextView) content[3]).getText().toString();
            // category changed? => Update categories!
            String currentCategory = ((TextView) currentContent[1]).getText().toString();
            if (!currentCategory.equals(category)) {
                // decrease count for previous category
                if (!currentCategory.equals(NEW_ITEM)) {
                    Integer count = categoryMap.get(currentCategory);
                    if (count.intValue() == 1)
                        categoryMap.remove(currentCategory);
                    else
                        categoryMap.put(currentCategory, new Integer(count.intValue() - 1));
                }
                // increase count for new category
                Integer count = categoryMap.get(category);
                if (count == null)
                    count = new Integer(0);
                categoryMap.put(category, new Integer(count.intValue() + 1));
            }
            ((CheckBox) currentContent[0]).setChecked(active);
            ((TextView) currentContent[1]).setText(category);
            ((TextView) currentContent[2]).setText(name);
            ((TextView) currentContent[3]).setText(url);
            if (newItem)
                newItem(editedRow);
            editDialog.dismiss();
            editDialog.findViewById(R.id.errorMsg).setVisibility(View.GONE);
        }
    }

    private void newItem(TableRow row) {
        addEmptyEndItem();
    }

    private void validateContent(View[] cells) throws Exception {
        try {
            String urlStr = ((TextView) cells[3]).getText().toString();
            if (!urlStr.startsWith("file://")) {
                URL url = new URL(urlStr);
                String shortTxt = ((TextView) cells[2]).getText().toString().trim();
                if (shortTxt.equals(NEW_ITEM) || shortTxt.equals(""))
                    ((TextView) cells[2]).setText(url.getHost());
                String category = ((TextView) cells[1]).getText().toString().trim();
                if (category.equals(NEW_ITEM) || category.equals(""))
                    ((TextView) cells[1]).setText(url.getHost());
            } else {
                File f = new File(urlStr.substring(7));
                String shortTxt = ((TextView) cells[2]).getText().toString().trim();
                if (shortTxt.equals(NEW_ITEM) || shortTxt.equals(""))
                    ((TextView) cells[2]).setText(f.getName());
                String category = ((TextView) cells[1]).getText().toString().trim();
                if (category.equals(NEW_ITEM) || category.equals(""))
                    ((TextView) cells[1]).setText(f.getName());
            }
        } catch (MalformedURLException e) {
            throw e;
        }
    }
}

16 Source : FilterConfig.java
with GNU General Public License v2.0
from IngoZenz

private void setVisibility(TableRow row) {
    String currentCategory = categoryField.getText().toString();
    String rowCategory = ((TextView) row.getVirtualChildAt(1)).getText().toString();
    boolean active = ((CheckBox) row.getVirtualChildAt(0)).isChecked();
    boolean visible = (currentCategory.equals(ALL_CATEGORIES)) || (currentCategory.equals(ALL_ACTIVE) && active) || (rowCategory.equals(NEW_ITEM)) || (rowCategory.equals(currentCategory));
    if (visible)
        row.setVisibility(View.VISIBLE);
    else
        row.setVisibility(View.GONE);
}

16 Source : HealthRenderManager.java
with Apache License 2.0
from HMS-Core

private TableRow initTableRow(String keyStr, String valueStr) {
    TextView textViewKey = new TextView(mContext);
    TextView textViewValue = new TextView(mContext);
    textViewKey.setText(keyStr);
    textViewValue.setText(valueStr);
    textViewValue.setPadding(PADDING_VALUE, 0, 0, 0);
    TableRow tableRow = new TableRow(mContext);
    tableRow.addView(textViewKey);
    tableRow.addView(textViewValue);
    return tableRow;
}

16 Source : MultiLineRadioGroup.java
with MIT License
from Gavras

// arrange the buttons in the layout
private void arrangeButtons() {
    // iterates over each button and puts it in the right place
    for (int i = 0, len = mRadioButtons.size(); i < len; i++) {
        RadioButton radioButtonToPlace = mRadioButtons.get(i);
        int rowToInsert = (mMaxInRow != 0) ? i / mMaxInRow : 0;
        int columnToInsert = (mMaxInRow != 0) ? i % mMaxInRow : i;
        // gets the row to insert. if there is no row create one
        TableRow tableRowToInsert = (mTableLayout.getChildCount() <= rowToInsert) ? addTableRow() : (TableRow) mTableLayout.getChildAt(rowToInsert);
        int tableRowChildCount = tableRowToInsert.getChildCount();
        // if there is already a button in the position
        if (tableRowChildCount > columnToInsert) {
            RadioButton currentButton = (RadioButton) tableRowToInsert.getChildAt(columnToInsert);
            // insert the button just if the current button is different
            if (currentButton != radioButtonToPlace) {
                // removes the current button
                removeButtonFromParent(currentButton, tableRowToInsert);
                // removes the button to place from its current position
                removeButtonFromParent(radioButtonToPlace, (ViewGroup) radioButtonToPlace.getParent());
                // adds the button to the right place
                tableRowToInsert.addView(radioButtonToPlace, columnToInsert);
            }
        // if there isn't already a button in the position
        } else {
            // removes the button to place from its current position
            removeButtonFromParent(radioButtonToPlace, (ViewGroup) radioButtonToPlace.getParent());
            // adds the button to the right place
            tableRowToInsert.addView(radioButtonToPlace, columnToInsert);
        }
    }
    removeRedundancies();
}

16 Source : TableLayout.java
with GNU General Public License v2.0
from Cloudslab

private void addChild(AndroidViewComponent child) {
    int row = child.Row();
    int col = child.Column();
    if (row == -1 || col == -1) {
        addChildLater(child);
    } else if (row < 0 || row >= this.numRows) {
        Log.e("TableLayout", "Child has illegal Row property: " + child);
    } else if (col < 0 || col >= this.numColumns) {
        Log.e("TableLayout", "Child has illegal Column property: " + child);
    } else {
        TableRow tableRow = (TableRow) this.layoutManager.getChildAt(row);
        tableRow.removeViewAt(col);
        View cellView = child.getView();
        tableRow.addView(cellView, col, cellView.getLayoutParams());
    }
}

16 Source : StandingTable.java
with Apache License 2.0
from brookmg

private void addRows(RankItem rankItem, TableRow... rows) {
    for (TableRow row : rows) {
        row.setOnClickListener(v -> {
            if (onTableRowClickedCallback != null && rankItem != null)
                onTableRowClickedCallback.onClick(rankItem.getTeam());
        });
        addView(row);
    }
}

16 Source : TicTacToeActivity.java
with MIT License
from bridgefy

protected void initializeBoard() {
    size = 3;
    board = new int[size][size];
    mainBoard = findViewById(R.id.mainBoard);
    tv_turn = findViewById(R.id.turn);
    if (myTurn) {
        tv_turn.setText(String.format(getString(R.string.your_turn), String.valueOf(myTurnChar)));
    } else {
        tv_turn.setText(String.format(getString(R.string.their_turn), rival.getNick(), String.valueOf(flipChar(myTurnChar))));
    }
    resetBoard(null);
    for (int i = 0; i < mainBoard.getChildCount(); i++) {
        TableRow row = (TableRow) mainBoard.getChildAt(i);
        for (int j = 0; j < row.getChildCount(); j++) {
            TextView tv = (TextView) row.getChildAt(j);
            tv.setOnClickListener(MoveListener(i, j, tv));
            tv.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.black));
        }
    }
}

16 Source : DisplayMnemonicActivity.java
with GNU General Public License v3.0
from Blockstream

private void setUpTable(final int id, final int startWordNum) {
    int wordNum = startWordNum;
    final TableLayout table = UI.find(this, id);
    for (int y = 0; y < table.getChildCount(); ++y) {
        final TableRow row = (TableRow) table.getChildAt(y);
        for (int x = 0; x < row.getChildCount() / 2; ++x) {
            ((TextView) row.getChildAt(x * 2)).setText(String.valueOf(wordNum));
            TextView me = (TextView) row.getChildAt(x * 2 + 1);
            me.setInputType(0);
            me.addTextChangedListener(new UI.Texreplacedcher() {

                @Override
                public void afterTextChanged(final Editable s) {
                    super.afterTextChanged(s);
                    final String original = s.toString();
                    final String trimmed = original.trim();
                    if (!trimmed.isEmpty() && !trimmed.equals(original)) {
                        me.setText(trimmed);
                    }
                }
            });
            registerForContextMenu(me);
            mTextViews[wordNum - 1] = me;
            ++wordNum;
        }
    }
}

16 Source : DeviceActivity.java
with MIT License
from bertrandmartel

/**
 * alternate colors for description rows
 *
 * @param alt_row
 */
public void altTableRow(int alt_row, TableLayout tablelayout) {
    int childViewCount = tablelayout.getChildCount();
    for (int i = 0; i < childViewCount; i++) {
        TableRow row = (TableRow) tablelayout.getChildAt(i);
        for (int j = 0; j < row.getChildCount(); j++) {
            TextView tv = (TextView) row.getChildAt(j);
            if (i % alt_row != 0) {
                tv.setBackground(getResources().getDrawable(R.drawable.alt_row_color));
            } else {
                tv.setBackground(getResources().getDrawable(R.drawable.row_color));
            }
        }
    }
}

15 Source : GameSelector.java
with GNU General Public License v3.0
from TobiasBielefeld

/**
 * Starts the clicked game. This uses the total index position of the clicked view to get the
 * game.
 *
 * @param view The clicked view.
 */
private void startGame(View view) {
    TableRow row = (TableRow) view.getParent();
    TableLayout table = (TableLayout) row.getParent();
    ArrayList<Integer> orderedList = lg.getOrderedGameList();
    int index = indexes.get(table.indexOfChild(row) * menuColumns + row.indexOfChild(view));
    index = orderedList.indexOf(index);
    // avoid loading two games at once when pressing two buttons at once
    if (prefs.getSavedCurrentGame() != DEFAULT_CURRENT_GAME) {
        return;
    }
    prefs.saveCurrentGame(index);
    Intent intent = new Intent(getApplicationContext(), GameManager.clreplaced);
    intent.putExtra(GAME, index);
    startActivityForResult(intent, 0);
}

15 Source : ReferenceCell.java
with Apache License 2.0
from theblackwidower

public static TableRow buildRow(Context context, Question[] questions) {
    if (questions == null)
        return null;
    else {
        TableRow row = new TableRow(context);
        for (Question question : questions) row.addView(question.generateReference(context));
        return row;
    }
}

See More Examples