如何从我从JavaClass创建的EditText中获取文本



im在Android Studio中是新的,我正试图从我从java类创建的EditText中获取文本,而不是在xml中可视化。该项目的主要想法是尝试做一个数独,所以我有:

  • 9x9表格
  • 81个数字的数组
  • 表中的一些方块有EditText,而另一些方块有TextViews(比如数独(

但问题是我不知道如何从EditText中获取文本,因为它们不是以正常方式创建的,所以我不能为实例

还有其他方法可以获取文本吗?

我的文件:

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_nivel.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 中获取文本

我不确定你不明白什么,但EditText实际上有一个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

要将它们全部保存在同一个数组中,请将它们保存为TextView,而不是EditText,因为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
}

最新更新