Android 2.1 getEditableText() возвращает пустую / пустую строку

У меня есть простое приложение, которое имеет одно поле edittext и одну кнопку. Кнопка, которую я хочу взять в значении поля edittext и сохранить его в строку (чтобы разобрать позже). Но я застрял даже при чтении значения с помощью метода getEditableText(). Я распечатываю значение в Log.d(), но оно кажется пустым или, по крайней мере, пустой строкой. Куда я иду не так?

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:text="@string/title"
        tools:context=".MainActivity" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:inputType="text"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:text="@string/button1"
        android:onClick="createarray" />

</RelativeLayout>

MainActivity.java

package com.example.hw1;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    int[] numberarray;

    public void createarray(View v){
       setContentView(R.layout.activity_main);
       //EditText editText1 = (EditText)findViewById(R.id.editText1);
       //Toast.makeText(this,editText1.getText().toString(),
       //Toast.LENGTH_SHORT).show();
       //String etoutput = editText1.getText().toString();
       String etoutput = ((EditText)findViewById(R.id.editText1)).getEditableText().toString().trim();
       Log.d("etoutput",etoutput);
       if(etoutput.length() > 0){
           Log.d("etoutput length","its got something");
       }
       else{
           Log.d("etoutput length","EMPTY!!");
       }
       //Log.d("etoutput","in here");
       //Log.d("etoutput",etoutput);
       String[] sepetoutput = etoutput.split("[\\s,]+");

       numberarray = new int[sepetoutput.length];

       for (int i=0;i<sepetoutput.length;i++){
           try{
               Log.d("i",Integer.toString(i));
               numberarray[i] = Integer.parseInt(sepetoutput[i]);
           }catch(NumberFormatException nfe){          

           }
       }

       Toast.makeText(this,"Array size: " + numberarray.length,
               Toast.LENGTH_SHORT).show();
      ((EditText)findViewById(R.id.editText1)).setText("123456");

    }
}

3 ответа

Решение

Вы вызываете setContentView() каждый раз, когда вы нажимаете button, Это действие сбросит EditText в состояние, которое вы определили в макете Xml (который пуст). Удалить эту строку на вашем createarray метод, и вы должны получить то, что вы хотите.

Ты пытался:

String etoutput = (EditText)findViewById(R.id.editText1)).getText().toString().trim();

Я думаю, что вы должны вызвать функцию createarray в процедуре OnCreate.

Другие вопросы по тегам