Android how to print a array in text view or anything

纵饮孤独 提交于 2019-11-27 16:55:28

问题


I have a array of words and I would like to print the array of words onto the screen in a text view after a button is clicked. i was using a for loop to go through the whole list and then set text, but i keep getting a error with that plus it will just replace the last value, so it wont print the whole array. If anybody could explain to me how to do like a g.drawSting() but android version that would be great. my code rt now is not with me but it something like: -I'm a beginner to android btw, probably could tell by this question tho.

public void onCreate(Bundle savedInstanceState)
{
//code for a button just being pressed{
 //goes to two methods to fix the private array{
     for(int y=0; y<=array.size()-1; y++){
        textArea.setText(aarray.get(y));   //prints all strings in the array
 }
}
}

回答1:


int arraySize = myArray.size();
for(int i = 0; i < arraySize; i++) {
myTextView.append(myArray[i]);
}

if you want to print one by one, then use \n

myTextView.append(myArray[i]);
myTextView.append("\n");

PS: Whoever suggesting to change .size() to .length(), thanks for you suggestion.

FYI, The questioner mentioned the variable name is array.size() in question, so the answer also having the same variable name, to make it easier for the questioner.

if your variable (myArray) is an Array use myArray.length(), if it is ArrayList use myArray.size()




回答2:


You have to combine all text into a String before you can give it the TextView. Otherwise you overwrite the text all the time.

public void onCreate(Bundle savedInstanceState)
{
     StringBuilder sb = new StringBuilder();
     int size = array.size();
     boolean appendSeparator = false;
     for(int y=0; y < size; y++){

        if (appendSeparator)
            sb.append(','); // a comma
        appendSeparator = true;

        sb.append(array.get(y));
     }
     textArea.setText(sb.toString());
}



回答3:


I use this no-index solution, just an easy to remember one liner:

for(File file:list) Log.d(TAG, "list: " + file.getPath());



来源:https://stackoverflow.com/questions/9668041/android-how-to-print-a-array-in-text-view-or-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!