2015-07-04 3 views
-1

ОБНОВЛЕНО: я заменил свой код тем, что вы мне дали, но у меня ошибка времени выполнения. Уточнить; У меня есть два TextViews со своим собственным идентификатором, но внутри нет текста. У меня также есть две объявленные строки (по одному для каждого TextView), каждая из которых я хочу, чтобы они сказали. Код берет эти строки и помещает их в мои TextViews для меня, а затем печатает строки по одной букве за раз с той скоростью, на которую я установил свою скорость.Сделать текст из TextView в String Error

Это мой текущий класс MainActivity.java:

package com.example.micor.projectsero2; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.TextView; 

import com.example.micor.projectsero2.util.LetterDisplay; 


public class MainActivity extends Activity { 
    public void onCreate(Bundle savedInstanceState){ 
     // ... 
     // you can do this in every method not only in onCreate e.g onStart onResume etc. 
     // now start LetterDisplay thread 
     TextView textView = (TextView) findViewById(R.id.loadView); // if you have another id of textView replace R.id.textView to your id 
     String text = getString(R.string.loadText); 
     int speed = 30; // you can change it to another value 

     LetterDisplay letterDisplay = new LetterDisplay(this, textView, text, speed); 
     letterDisplay.start(); // now LetterDisplay thread is running 
     // EDIT: and start next LetterDisplay thread for second textView 
     String secondText = getString(R.string.prelogText); 
     TextView secondTextView = (TextView) findViewById(R.id.prelogView); // replace R.id.second_text_view with your id of second textView 
     letterDisplay = new LetterDisplay(this, secondTextView, secondText, speed); 
     letterDisplay.start(); 
     // and now two threads is running and updates textViews 

    } 
@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_main, 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.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 
} 

UPDATE: Это мой LetterDisplay класс:

public class LetterDisplay extends Thread { 

private Activity mActivity; 
private TextView textView; 
private String text; 
private int charCount; 
private int currentLetterCount = 0; 
private int speed; // How fast should it type? 
private boolean isRunning = true; 



public LetterDisplay(Activity activity, TextView textView, String text, int speed){ 
    mActivity = activity; 
    this.textView = textView; 
    this.text = text; 
    this.speed = speed; 
} 
public void run(){ 
    while(currentLetterCount < charCount && isRunning){ 
     String currentText = textView.getText().toString(); 
     char currentLetter = text.charAt(currentLetterCount++); 
     final String textToUpdate = currentText + currentLetter; 
     mActivity.runOnUiThread(new Runnable(){ 
      public void run(){ 
       textView.setText(textToUpdate); 
      } 
     }); 
     try 
     { 
      Thread.sleep(speed); 
     } catch(InterruptedException e){} 
    } 
    isRunning = false; 
} 
public void stopThread(){ 
    isRunning = false; 
} 
public boolean isRunning(){ 
    return isRunning; 
} 
} 

Logcat из Run:

07-05 12:40:08.348 23286-23286/? E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.micor.projectsero2, PID: 23286 
android.util.SuperNotCalledException: Activity  {com.example.micor.projectsero2/com.example.micor.projectsero2.MainActivity} did not call through to super.onCreate() 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441) 
     at android.app.ActivityThread.access$800(ActivityThread.java:162) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5431) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706) 

07-05 12 : 40: 08.348 3308-3329 /? D/KeyguardUpdateMonitor: isSimPinSecure() return false 07-05 12: 40: 08.348 1079-3332 /? W/ActivityManager: принудительная завершающая деятельность 1 com.example.micor.projectsero2/.MainActivity 07-05 12: 40: 08.358 3308-4541 /? D/KeyguardUpdateMonitor: isSimPinSecure() возвращают ложные

+0

Вы хотите запустить этот код на двух текстовых элементах, я прав? – krystian71115

+0

И если я хочу сделать больше двух, я бы повторил тот же кусок кода с 'String thirdText' и' TextView thirdTextView' и т. Д., Предполагая, что я заменю все переменные? – micoror1

+0

Созданы два метода с такими же именами и параметрами. Этот код не может быть скомпилирован с кодового кода с первого раза на CreateCreatate на second onCreate и удалить пустой метод onCreate. И замените 'String test =" @ string/test ";' с: 'String test = getString (R.string.test);' – krystian71115

ответ

1

Попробуйте этот метод String currentText = loadView.getText().toString();

GetText() не принимает никаких аргументов и возвращает CharSequence. CharSequence не может применяться к String, который вы должны вызвать toString().

Edit: FIXED LetterDisplay класс:

public LetterDisplay(Activity activity, TextView textView, String text, int speed){ 
    mActivity = activity; 
    if(mActivity == null){ 
     throw new IllegalArgumentException("activity cannot be null in LetterDisplay"); 
    } 
    this.textView = textView; 
    if(textView == null){ 
     throw new IllegalArgumentException("textView cannot be null in LetterDisplay"); 
    } 
    this.text = text; 
    if(text == null){ 
     throw new IllegalArgumentException("text cannot be null in LetterDisplay"); 
    } 
    this.speed = speed; 
    if(speed <= 0){ 
     throw new IllegalArgumentException("speed cannot be lower or equals than 0"); 
    } 
    this.charCount = text.length(); 
    if(charCount == 0){ 
     // no error but i print the warning into logcat 
     Log.w("LetterDisplay", "The text in the LetterDisplay is empty and nothing will be executed"); 
    } 
} 
public void run(){ 
    if(charCount > 0) 
     textView.setText(""); // Clear the text if any exists 
    while(currentLetterCount < charCount && isRunning){ 
     final String textToUpdate = text.substring(0, ++currentLetterCount); 
     mActivity.runOnUiThread(new Runnable(){ 
      public void run(){ 
       textView.setText(textToUpdate); 
      } 
     }); 
     try 
     { 
      Thread.sleep(speed); 
     } catch(InterruptedException e){} 
    } 
    isRunning = false; 
} 
public void stopThread(){ 
    // you can call it in onPause or onStop or in onDestroy method to stop the thread and avoid energy consumption 
    isRunning = false; 
} 
public boolean isRunning(){ 
    // if you want to check if thread is running 
    return isRunning; 
} 
} 

И теперь в вашей деятельности:

public class MyActivity extends Activity { 
     public void onCreate(Bundle savedInstanceState){ 
      // ... 
      // you can do this in every method not only in onCreate e.g onStart onResume etc. 
      // now start LetterDisplay thread 
      TextView textView = (TextView) findViewById(R.id.textView); // if you have another id of textView replace R.id.textView to your id 

      String text = "Text to show. You can change it"; 
      int speed = 100; // you can change it to another value 

      LetterDisplay letterDisplay = new LetterDisplay(this, textView, text, speed); 
      letterDisplay.start(); // now LetterDisplay thread is running 
      // EDIT: and start next LetterDisplay thread for second textView 
      String secondText = "Second text to show"; 
      TextView secondTextView = (TextView) findViewById(R.id.second_text_view); // replace R.id.second_text_view with your id of second textView 
      letterDisplay = new LetterDisplay(this, secondTextView, secondText, speed); 
      letterDisplay.start(); 
      // and now two threads is running and updates textViews 

     } 

} 
+0

Это не дало мне ошибку, но я хочу получить loadText из loadView, но 'String currentText = loadView.getText (loadText) .toString();' дает ту же ошибку. EDIT: я не видел вашего редактирования – micoror1

+0

, что вы имеете в виду, когда говорите, что хотите «загрузить loadText из loadView»? – Adeeb

+0

Он, похоже, не работает в целом, но я не могу найти причину, по которой приложение будет разбито на открытом. Там где-то ошибка времени выполнения, которую я не вижу. – micoror1

3

Тип того, что вы пытаетесь получить не тип String, поэтому вы должны добавить " toString ". Кроме того, метод getText не работает с параметрами, поэтому он должен быть:

String currentText = loadView.getText().toString(); 
+0

Я пробовал это раньше, дает мне ту же ошибку: «getText в TextView нельзя применить к java.lang.String», все еще подчеркивая (loadText). – micoror1

+0

попробуйте мой фиксированный ответ, спасибо krystian71115 –

+0

Так что бы это захватить loadText из loadView и превратить его в строку? – micoror1

Смежные вопросы