Update text view from Android function

can anyone tell me how to update Android Textview control from function? I searched deep into the Internet and I see many people asking the same question, I tested topics, but could not work, does anyone have a simple working example of this? for example, to call a function (which is executed several times in a loop), and the function writes to the TextView, but the problem is that until the function is completed, it will show me the text.

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

    while(condition) //here freezes the UI and the text in textview only shows when the loop ends
    {
        HardWork();  
    }

}

public void HardWork() {  

    txtProgreso.append("Test Line" + "\n\n");

};

Thanks in advance.

+3
source share
3 answers

AsyncTask, textview onProgressUpdate

private class SomeTask extends AsyncTask<String, String, String> {
    @Override
        protected String doInBackground(String... params) {
         while(condition) {
         //do more
         publishProgress("Some text value to you textview");
        }
         return null;
     }

     @Override
     protected void onProgressUpdate(String... values) {
         txtProgreso.append(values[0]);
     }


 }
+5

, : " TextView runloop?" (.. ).

, , , Android UI. , , - , TextView.

. , " " TextView, :

private Handler mHandler = new Handler();
private String desiredText = new String("This is a test");

private Runnable mUpdateTextView = new Runnable() {
  public void run() {
    TextView textView = (TextView)findViewById(R.id.myTextView);
    int lengthSoFar = textView.getText().length();
    if (lengthSoFar < desiredText.length()) {
      mTextView.setText(desiredText.substring(0, lengthSoFar + 1));
      mHandler.postDelayed(100, mUpdateTextView);
    }
  }
};

protected void onStart() {
  mHandler.postDelayed(100, mUpdateTextView);
}

, , Android, , . , , , .

+3

, .

TextView myTextView = (TextView)findViewById(R.id.textViewsId);

Then after that you can change the TextView using functions. For example, you can set the text using the following code.

myTextView.setText("New text example");

Are there any other updates for the control you are trying to do?

+1
source

Source: https://habr.com/ru/post/1776993/


All Articles