如何将对象数组列表中的Text设置为TextView?

时间:2019-05-17 12:41:50

标签: java android arraylist textview

我正在尝试使用setText方法来显示从ArrayList的{​​{1}}到Objects的所有元素。

我在6个不同的架子(A,B,C,D,E,F)中有6个按钮,每个架子都有一个弹出菜单,用户在其中选择了一个基点(N,S,E,W),然后在文本视图中显示搁置字母和单击的项目。这是地图:

这是我正在使用的代码:

TextView

这是类Button buttonA, buttonB, buttonC, buttonD, buttonE, buttonF; private TextView coordenada_view; ArrayList<PickUpPoint> pickuppoint_array = new ArrayList<PickUpPoint>(); @Override protected void onCreate{...... buttonA.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final PopupMenu popupMenu = new PopupMenu(Mapa.this, buttonA); popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { String mShelving = buttonA.getText().toString(); String mCardinalPoint = item.getTitle().toString(); pickuppoint_array.add(new PickUpPoint(mShelving,mCardinalPoint)); PickUpPoint pickUpPoint = new PickUpPoint(mShelving,mCardinalPoint); //Here I´m trying to show all the elements of the ArrayList into the TextView for (int i = 0; i < pickuppoint_array.size(); i++){ coordenada_view.setText( pickuppoint_array.get(i).toString()); } return true; } }); popupMenu.show(); buttonB.setOnClickListener.... buttonC.setOnClickListener.... }

PickUpPoint

但是我是从数组列表中得到的:

所以,我的问题是...如何从像这样的数组列表中获取所有元素?

2 个答案:

答案 0 :(得分:0)

我假设coordenada_view#setText只能被调用一次。

因此您需要先将Pickuppoint_array中的Elements转换为String 然后将其提供给setText方法。

StringBuilder content = new StringBuilder();
for (int i = 0; i < pickuppoint_array.size(); i++) {
  content.append(pickuppoint_array.get(i).toString());
  content.append('\n');
}

coordenada_view.setText(content.toString());

您还希望在PickUpPoint类中实现toString()方法,以返回每个对象的所需表示形式,例如:

public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("SHELVING ");
    builder.append(shelving);
    builder.append(" - ");
    builder.append(cardinalPoint);
    return builder.toString();
}

Ps .: 如果您知道这些字符串的预期长度,则应将其作为参数提供给StringBuilder构造函数,因此jvm无需浪费时间来调整其大小。

新的StringBuilder(18)可能适用于toString方法, 并且新的StringBuilder(19 * Pickuppoint_array.size())可能适用于另一个。

答案 1 :(得分:0)

使用此方法设置Arraylist

中的文本

还要检查Arraylist是否不是null并为空

public void setTextViewFromList(ArrayList<PickUpPoint> arraylist, TextView textview) {
    //Variable to hold all the values
    String output = "";

    for (int i = 0; i < arraylist.size(); i++) {
        //Append all the values to a string
        output += arraylist.get(i).getShelving();//whatever you want to show here like shelving or cordinalpoint use getCordinalPoint()
        output += "\n";
    }

    //Set the textview to the output string
   textview.setText(output);
}

用法

像这样调用此方法

setTextViewFromList(pickuppoint_array,coordenada_view)