2013-07-02 4 views
1

Я знаком с Android, и я хочу поместить текст в TextView последовательно, с известным временем между символами, из написанного текста в EditTextКак установить TextView из ArrayList, символа по символу, последовательно

Это решение, которое я сделал: Я написал два массива ArrayList, заряженных из EditText, первый из которых содержит символы из EditText, второй - с Integer для определения времени между символами. Затем я анализирую ArrayLists, раз загрузка целых чисел выполняется последовательно, но не символы, TextViews рисуются только тогда, когда цикл заканчивается.

Мой код MainActivity:

import java.util.ArrayList; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

private TextView showCharacter; 
private TextView showAppendCharacter; 
private EditText incomingText; 
private Button readTextEdit; 

private ArrayList<CharSequence> toText = new ArrayList<CharSequence>(); 
private ArrayList<Integer> timePlay = new ArrayList<Integer>(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    showCharacter = (TextView) findViewById(R.id.showCharacterTextView); 
    showAppendCharacter = (TextView) findViewById(R.id.showAppendCharacterTextView); 
    incomingText = (EditText) findViewById(R.id.incomingEditText); 
    readTextEdit = (Button) findViewById(R.id.readTextButton); 

    readTextEdit.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      toText.clear(); 
      timePlay.clear(); 
      showAppendCharacter.setText(""); 

      String text = incomingText.getText().toString(); 
      for (int base = 0; base < text.length(); base++) { 
       if (String.valueOf(text.charAt(base)).equals("a")) { 
        toText.add(("a")); 
        timePlay.add(500); 
       } else if (String.valueOf(text.charAt(base)).equals("b")) { 
        toText.add(("b")); 
        timePlay.add(650); 
       } else if (String.valueOf(text.charAt(base)).equals("c")) { 
        toText.add(("c")); 
        timePlay.add(800); 
       } else { 
        toText.add(("_")); 
        timePlay.add(1000); 
       } 
      } 

      for (int pos = 0; pos < toText.size(); pos++) { 
       try { 
        Thread.sleep(timePlay.get(pos)); 
        showCharacter.setText((String) toText.get(pos)); 
        showAppendCharacter.append((String) toText.get(pos)); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }); 
} 
} 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/LinearLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/showCharacterTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/showCharacterTextView" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<TextView 
    android:id="@+id/showAppendCharacterTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/showAppendCharactersTextView" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<EditText 
    android:id="@+id/incomingEditText" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:ems="10" 
    android:hint="@string/incomingTextEditText" 
    android:inputType="text" > 

    <requestFocus /> 
</EditText> 

<Button 
    android:id="@+id/readTextButton" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/readButton" /> 

strings.xml:

<?xml version="1.0" encoding="utf-8"?> 

<string name="app_name">texto Desde ArrayList</string> 
<string name="action_settings">Settings</string> 
<string name="showCharacterTextView">Show last Character</string> 
<string name="showAppendCharactersTextView">Show append Characters</string> 
<string name="incomingTextEditText">Incoming text</string> 
<string name="readButton">Read text</string> 

Любые предложения ?? Буду признателен за любые идеи.

ответ

0

Попробуйте что-нибудь вроде этого ... Вы можете избавиться от арраистов. Помните, что String представляет собой массив символов. создайте пользовательский текстовый вид, который реализует runnable, поэтому работа, которую вы пытаетесь сделать с текстом, не выполняется в основном потоке.

package com.example.stackquestion; 

import java.util.ArrayList; 

import android.content.Context; 
import android.graphics.Color; 
import android.os.SystemClock; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class CustomTextView extends TextView implements Runnable { 
    String text  = null; 
    int  i   = 0; 
    int  length  = 0; 
    String currentText = ""; 

    public CustomTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     reset(); 
    } 

    @Override 
    public void run() { 

     if (i < length) { 
      currentText = currentText + text.charAt(i); 
      setText(currentText); 
      if (text.charAt(i) == 'a') { 
       postDelayed(this, 500); 
      } else if (text.charAt(i) == 'b') { 
       postDelayed(this, 650); 
      } else if (text.charAt(i) == 'c') { 
       postDelayed(this, 800); 
      } else if (text.charAt(i) == '_') { 
       postDelayed(this, 1000); 
      } else 
       postDelayed(this, 1); 
      i++; 
     } 
    } 

    public void setString(String text) { 
     this.text = text; 
     this.length = text.length(); 
    } 

    public void reset() { 
     currentText = ""; 
     text = null; 
     i = 0; 
     setText(""); 
    } 
} 

Вот основное направление деятельности

package com.example.stackquestion; 

import java.util.ArrayList; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    private TextView    showCharacter; 
    private CustomTextView   showAppendCharacter; 
    private EditText    incomingText; 
    private Button     readTextEdit; 

    private ArrayList<CharSequence> toText  = new ArrayList<CharSequence>(); 
    private ArrayList<Integer>  timePlay = new ArrayList<Integer>(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     showCharacter = (TextView) findViewById(R.id.showCharacterTextView); 
     showAppendCharacter = (CustomTextView) findViewById(R.id.showAppendCharacterTextView); 
     incomingText = (EditText) findViewById(R.id.incomingEditText); 
     readTextEdit = (Button) findViewById(R.id.readTextButton); 

     readTextEdit.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       if (v.getId() == R.id.readTextButton) 
        showAppendCharacter.reset(); 
       showAppendCharacter 
         .setString(incomingText.getText().toString()); 
       showAppendCharacter.run(); 
      } 
     }); 
    } 
} 

Woops. Я забыл дать вам макет. Но похоже, что ты понял. Просто измените тип textview на полностью соответствующий CustomTextView. Здесь был мой.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".MainActivity" > 

    <TextView 
     android:id="@+id/showCharacterTextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/showCharacterTextView" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <com.example.stackquestion.CustomTextView 
     android:id="@+id/showAppendCharacterTextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/showAppendCharactersTextView" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <EditText 
     android:id="@+id/incomingEditText" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:ems="10" 
     android:hint="@string/incomingTextEditText" 
     android:inputType="text" > 

     <requestFocus /> 
    </EditText> 

    <Button 
     android:id="@+id/readTextButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/readButton" /> 

</LinearLayout> 

Счастливый Coding :)

+0

здорово! работает! Благодаря! в начале у меня была ошибка java.lang.ClassCastException: android.widget.TextView нельзя отнести к com.prueba.textodesdearraylist.CustomTextView, затем я изменил в макете xml Rafix