如何将字符串数组转换为textview数组?

时间:2016-01-27 21:16:04

标签: java android arrays

我有一个字符串数组,如下所示,重新格式化它以获取TextView数组的最佳方法是什么

public static List<AthenaPanel> getData()  {

    //created an object for ur Drawer recyclerview array
    List<AthenaPanel> data= new ArrayList<>();
    //this is where you would add all your icons for the drawer list
    //arrays of icons
    int[] icons={R.drawable.ic_search_black_24dp};

    String[] titles = { "MyQuestions","     MyAnswers","     Calendar","     Setting","     Send FeedBack"};
    //this is our for loop to cycle through the icons and the titles
    for(int i=0;i<5;i++){
        AthenaPanel current=new AthenaPanel();

        //i%().length allows ups to loop over the array any number of times we want to
        current.iconId=icons[i%icons.length];
        current.title=titles[i%titles.length];
        data.add(current);
    }
    return data;
}

这是我的班级

public class AthenaPanel {
int iconId;
String title;

}

1 个答案:

答案 0 :(得分:0)

我不知道你想要实现什么而没有更多的细节,我的想法是有一种不同的方式来得到你想要的,但我还是要回答这个问题。

在这种情况下,我想您希望生成尽可能多的文本视图,因为AthenaPanel返回了getData()个对象,最好不要将布局限制为xml中定义的确定数量的TextView。相反,从xml中删除所有TextView标记并留空LinearLayout 您应该使用基本上下文创建相同数量的TextView

public List<TextView> createTextViews(Context context, List<AthenaPanel> athenaPanelList) {
   ArrayList<TextView> textViewList = new ArrayList<>();

   if(athenaPanelList != null && athenaPanelList.size() > 0) {
      for(AthenaPanel athenaPanel : athenaPanelList) {
         TextView textView = new TextView(context);
         textView.setText(athenaPanel.getTitle());
         textViewList.add(textView);
      }
   }

   return textViewList;
}

并调用该方法将视图添加到LinearLayout。让我们在您的活动中说出线性布局:

LinearLayout myLinearLayout = findViewById(R.id.myLinearLayout);
ArrayList<TextView> textViews = createTextViews(this, getData());
for(TextView textView : textViews){
   myLinearLayout.addView(textView);
}

如果您不希望他们使用根布局中的默认LayoutParams,则需要为TextView's指定LayoutParams。 LinearLayout实际上可以是ViewGroup的任何子类,即FrameLayout,RelativeLayout ......

如果您唯一想要的是将String数组转换为TextView数组:

String[] titles = { "MyQuestions","     MyAnswers","     Calendar","     Setting","     Send FeedBack"};
TextView[] textViews = new TextView[titles.length];
for(int i=0; i < titles.length; i++){    // I'd suggest to use lenght propery rather than 5 value
   TextView textView = new TextView(context);
   textView.setText(athenaPanel.getTitle());
   textViews[i] = textView;
}