簡體   English   中英

如何從我從JavaClass創建的EditText中獲取文本

[英]How to getText from EditText that i created from a JavaClass

我是Android Studio中的新手,我正在嘗試從我從java類創建的EditText中獲取文本,而不是在xml中可視化。 該項目的主要想法是嘗試做一個數獨,所以我有:

  • 9x9表
  • 包含81個數字的數組
  • 表格的某些正方形有一個EditText和其他TextViews(如數獨)

但問題是我不知道如何從EditText中執行getText,因為它們不是以正常方式創建的,所以我不能做“r.id.edittext_1”。

getText有另一種方法嗎?

我的文件:

tabla.java (我在哪里創建表以及所有EditText和TextView)

public class Tabla{
// Variables de la clase

private TableLayout tabla;          // Layout donde se pintará la tabla
private ArrayList<TableRow> filas;  // Array de las filas de la tabla
private Activity actividad;
private Resources rs;
private int FILAS, COLUMNAS;        // Filas y columnas de nuestra tabla

/**
 * Constructor de la tabla
 * @param actividad Actividad donde va a estar la tabla
 * @param tabla TableLayout donde se pintará la tabla
 */
public Tabla(Activity actividad, TableLayout tabla)
{
    this.actividad = actividad;
    this.tabla = tabla;
    rs = this.actividad.getResources();
    FILAS = COLUMNAS = 0;
    filas = new ArrayList<TableRow>();
}

/**
 * Añade la cabecera a la tabla
 * @param recursocabecera Recurso (array) donde se encuentra la cabecera de la tabla
 */
public void agregarCabecera(int recursocabecera)
{
    TableRow.LayoutParams layoutCelda;
    TableRow fila = new TableRow(actividad);
    TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    fila.setLayoutParams(layoutFila);

    String[] arraycabecera = rs.getStringArray(recursocabecera);
    COLUMNAS = arraycabecera.length;

    for(int i = 0; i < arraycabecera.length; i++)
    {
        TextView texto = new TextView(actividad);
        layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(arraycabecera[i]), TableRow.LayoutParams.WRAP_CONTENT);
        texto.setText(arraycabecera[i]);
        texto.setGravity(Gravity.CENTER_HORIZONTAL);
        texto.setTextAppearance(actividad, R.style.estilo_celda);
        //texto.setBackgroundResource(R.drawable.tabla_celda_cabecera);
        texto.setLayoutParams(layoutCelda);

        fila.addView(texto);
    }

    tabla.addView(fila);
    filas.add(fila);

    FILAS++;
}

/**
 * Agrega una fila a la tabla
 * @param elementos Elementos de la fila
 */
public void agregarFilaTabla(ArrayList<Integer> elementos)
{
    TableRow.LayoutParams layoutCelda;
    TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    TableRow fila = new TableRow(actividad);
    fila.setLayoutParams(layoutFila);

    for(int i = 0; i< elementos.size(); i++)
    {
        //Log.v("RESULTADO","X:"+String.valueOf(elementos.get(i)));
        if(elementos.get(i) == 0){
            EditText texto = new EditText(actividad); //FUNCION PARA PODER EDITAR
            //texto.setText(String.valueOf(elementos.get(i))); //FUNCION PARA ESCRIBIR NUMERO ARRAY
            //texto.getText().clear(); //FUNCION PARA BORRAR EL TEXTO
            texto.setGravity(Gravity.CENTER_HORIZONTAL); //FUNCION PARA ALINEAR
            texto.setInputType(2); //FUNCION PARA QUE SE PUEDA EDITAR CON NUMEROS SOLO
            texto.setTextAppearance(actividad, R.style.estilo_editables); //FUNCION PARA CARGAR EL COLOR DEL TEXTO
            texto.setFilters(new InputFilter[] {new InputFilter.LengthFilter(1)}); //FUNCION PARA LIMITAR LA CANTIDAD DE TEXTO
            texto.setBackgroundResource(R.drawable.tabla_celda);
            layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), TableRow.LayoutParams.WRAP_CONTENT);
            texto.setLayoutParams(layoutCelda);
            fila.addView(texto);
        }else{
            TextView texto = new TextView(actividad);
            texto.setText(String.valueOf(elementos.get(i)));
            texto.setGravity(Gravity.CENTER_HORIZONTAL);
            //texto.setInputType(0); //FUNCION PARA QUE NO SE PUEDA EDITAR, SOLO APLICAR A EDITTEXT
            texto.setTextAppearance(actividad, R.style.estilo_celda);
            texto.setBackgroundResource(R.drawable.tabla_celda);
            layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), TableRow.LayoutParams.WRAP_CONTENT);
            texto.setLayoutParams(layoutCelda);
            fila.addView(texto);
        }

    }

    tabla.addView(fila);
    filas.add(fila);

    FILAS++;
}

/**
 * Elimina una fila de la tabla
 * @param indicefilaeliminar Indice de la fila a eliminar
 */
public void eliminarFila(int indicefilaeliminar)
{
    if( indicefilaeliminar > 0 && indicefilaeliminar < FILAS )
    {
        tabla.removeViewAt(indicefilaeliminar);
        FILAS--;
    }
}

/**
 * Devuelve las filas de la tabla, la cabecera se cuenta como fila
 * @return Filas totales de la tabla
 */
public int getFilas()
{
    return FILAS;
}

/**
 * Devuelve las columnas de la tabla
 * @return Columnas totales de la tabla
 */
public int getColumnas()
{
    return COLUMNAS;
}

/**
 * Devuelve el número de celdas de la tabla, la cabecera se cuenta como fila
 * @return Número de celdas totales de la tabla
 */
public int getCeldasTotales()
{
    return FILAS * COLUMNAS;
}

/**
 * Obtiene el ancho en píxeles de un texto en un String
 * @param texto Texto
 * @return Ancho en píxeles del texto
 */
private int obtenerAnchoPixelesTexto(String texto)
{
    Paint p = new Paint();
    Rect bounds = new Rect();
    p.setTextSize(50);

    p.getTextBounds(texto, 0, texto.length(), bounds);
    return 100;
}

public int compararSolucion(ArrayList[] bueno , ArrayList[] usuario){
    if(bueno == usuario){
        return 1; //Correcto
    }else{
        return 0; //Malo
    }
}
}

nivel1.java (活動類)

public class nivel1 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nivel1);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    ArrayList<Integer> suddoku = new ArrayList<Integer>();
    Integer[] otherList = new Integer[] {0,0,0,0,0,0,0,8,4,5,0,0,0,4,2,6,0,0,0,0,4,0,0,0,0,2,0,0,4,0,0,6,3,7,0,0,0,0,0,0,0,1,0,0,3,6,3,0,9,5,7,2,0,0,0,5,0,0,0,9,0,0,6,3,2,0,8,0,0,1,0,9,0,0,9,5,0,0,8,0,0};
    Integer[] correctList = new Integer[] {7,9,2,6,1,5,3,8,4,5,8,3,7,4,2,6,9,1,1,6,4,3,9,8,5,2,7,9,4,8,2,6,3,7,1,5,2,7,5,4,8,1,9,6,3,6,3,1,9,5,7,2,4,8,8,5,7,1,2,9,4,3,6,3,2,6,8,7,4,1,5,9,4,1,9,5,3,6,8,7,2};
    suddoku.addAll(Arrays.asList(otherList));

    Tabla tabla = new Tabla(this, (TableLayout)findViewById(R.id.tabla));
    tabla.agregarCabecera(R.array.cabecera_tabla);
    int x = 0;
    int contador = 0;
    for(int i = 0; i < 9; i++)
    {
        ArrayList<Integer> elementos = new ArrayList<Integer>();
        for(x = x; contador < 9; contador++){
            elementos.add(suddoku.get(x));
            x++;
        }
        contador = 0;

        tabla.agregarFilaTabla(elementos);


    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_sudokus, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.resolvertop) {
        return true; //I want when you push this button, you get the text from all the EditText and put in an array, then compare with the complete array.
    }

    return super.onOptionsItemSelected(item);
}


public boolean onSupportNavigateUp() {
    onBackPressed();
    return false;
}
}

content_nivel1.xml (活動布局)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".nivel1"
tools:showIn="@layout/activity_nivel1">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="8"
        android:id="@+id/layoutTexto">

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/layoutTabla"
        android:gravity="center">

        <ScrollView
            android:id="@+id/scrollvertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:layout_weight="1">

            <HorizontalScrollView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/scrollhorizontal"
                android:scrollbars="horizontal"
                android:layout_weight="1">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TableLayout
                        android:id="@+id/tabla"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                    </TableLayout>
                </LinearLayout>

            </HorizontalScrollView>
        </ScrollView>

    </LinearLayout>

</LinearLayout>

</android.support.constraint.ConstraintLayout>

將此函數添加到Tabla類

 public String returnText(String tag){
    EditText texto = (EditText)tabla.findViewWithTag(tag);

    return texto.getText().toString();
 }

並從nivel1類調用它

 String texto = tabla.returnText(tag);

謝謝大家的時間和幫助。

當您使用row / col創建EditText setTag時。

EditText texto = new EditText(actividad);
textTo.setTag(row+col);

當你想要getText()

EditText texto = (EditText)tabla.findViewWithTag(row+col);
textto.getText()

我不知道怎么從EditText做一個getText

我不確定你不明白但是EditTexts確實有一個getText()方法。 它返回一個Editable並從中獲取字符串,你只需要調用toString()就可以了。

您需要找到一些訪問EditText對象的方法。 我建議你在Tabla.class中使用一個方法。 像這樣的東西:

public class Tabla {

    public TextView getViewAt(int row, int column) {
        return (TextView) filas.get(row).getChildAt(column);
    }
}

最簡單的方法是將所有EditText保存在數組中,就像其他數據一樣。

EditText[][] ets = new EditText[9][9];

在您的成員字段中並在循環內逐個分配。

我無法理解你的語言,所以我只想寫一個簡單的例子。

for(int y=0; y<9; y++) {
    for(int x=0; x<9; x++) {
        EditText et = ets[y][x] = new EditText(...);
        // initialize, attatch listeners to et
    }
}

編輯

所以你有一些 EditText一些 TextViews

要將它們全部保存在同一個數組中,而不是EditText ,請將它們保存為TextView因為TextViewEditText的超類。

所以它會是這樣的

TextView[][] tvs = new TextView[9][9];


// ...


for(int y=0; y<9; y++) {
    for(int x=0; x<9; x++) {
        if( fixed[y][x] ) { // check if the number of the cell is fixed.
            tvs[y][x] = new TextView(...);
            // Initialize tvs[y][x];
        } else {
            tvs[y][x] = new EditText(...);
            // initialize, attatch listeners to tvs[y][x];
        }
    }
}

稍后,您可以檢查fixed[y][x]以檢查是否有EditTextTextView ,如果它是EditText ,則像EditText et = (EditText) tvs[y][x];

或者,檢查喜歡的instance of

if(tvs[y][x] instanceof EditText) {
     EditText et = (EditText) tvs[y][x];
     // do something with et
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM