有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过while循环计算文本视图?

我正在编写一个小应用程序,从Web服务器以字符串的形式获取数据。我在正则表达式中拆分了这个字符串。我从来都不知道我会得到多少分离的字符串

在主屏幕上,我有10个文本视图。我想用来自Web服务器的数据填充该文本视图。但并非每次都有每个textView的数据。我将数据作为一个字符串,并将其拆分为多个字符串,但我以前从未考虑过多少个字符串(最多10个)。那么,我如何设置一个while循环,用一个变量来计算我的文本视图呢

布局中的文本视图的名称为textView1、textView2、textView3、textView4等等。我猜java文件中的textView[n]不是正确的方法,但是如何做到这一点呢

private TextView textView1;
private TextView textView2;
...

...
public void onResponseSuccessful(String processedResponse) {

   final String[] separated = processedResponse.split("Step: ");
   int n = separated.length;
   do {
      textView[n].append(separated[n]);
      n--;
   } while (n > 0);

// When I do it like that the TextView is underlined red, saying "Array type expected; found '安卓.widget.TextView'

共 (2) 个答案

  1. # 1 楼答案

    您是否已添加textView1、textView2等。。。数组[] 像这样:

    TextView[] textView = {textView1,textView2,....};
    
    final String[] separated = processedResponse.split("Step: ");
    int n = separated.length;
      do {
          textView[n].append(separated[n]);
          n ;
      } while (n > 0);
    
  2. # 2 楼答案

    最好使用ListView,但也可以按自己的方式: (本例使用3文本视图,但您可以使用10)

    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    
    private TextView[] textViews = {textView1, textView2, textView3};
    
    public void onResponseSuccessful(String processedResponse) {
    
        final String[] separated = processedResponse.split("Step: ");
    
        for (int i = 0; i < textViews.length; i++) {
            if (i < separated.length) {
                textViews[i].setText(separated[i]);
                textViews[i].setVisibility(View.VISIBLE);
            } else {
                textViews[i].setVisibility(View.GONE);
            }
    
        }
    }
    

    请注意,您需要使用findviewbyd()或其他东西初始化这些文本视图