I am trying to do something simple: display my ArrayList to a TextView. I have tried to use methods that would do this without success. Or am I supposed to use a ListView instead of a TextView?
Anyway here is the code. I hope someone can help.
public class MainActivity extends Activity {
Button aButton; // Global Scope
TextView text2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
aButton = (Button) this.findViewById(R.id.button1);
aButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<String> list = new ArrayList<String>();
list.add("Books");
list.add("Newspapers");
list.add("Magazines");
for (int i = 0; i < list.size(); i++) {
//System.out.println(list.get(i));
Log.i("Results", list.get(i));
text2.setText(text2.getText());
}
}
});
}
You are not changing text of TexView:
text2.setText(text2.getText());
You rather thought about:
text2.setText(list.get(i));
eventually:
text2.setText((text2.getText() != null ? text2.getText() : "") + list.get(i));
try this :
aButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<String> list = new ArrayList<String>();
list.add("Books");
list.add("Newspapers");
list.add("Magazines");
String listString = "";
for (String s : list) {
listString += s + " ";
}
text2.setText(listString);
}
});
Your prolem is here
text2.setText(text2.getText())
The working code will be:
public class MainActivity extends Activity {
Button aButton; // Global Scope
TextView text2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
aButton = (Button) this.findViewById(R.id.button1);
aButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<String> list = new ArrayList<String>();
list.add("Books");
list.add("Newspapers");
list.add("Magazines");
for (int i = 0; i < list.size(); i++) {
//System.out.println(list.get(i));
Log.i("Results", list.get(i));
text2.setText(list.get(i));
}
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.