繁体   English   中英

在RelativeLayout中动态添加TextView

[英]Adding TextView dynamically in RelativeLayout

我正在使用以下代码。 代码应在一行中显示值的值,例如,如果values[]包含{A,B,C,D,E,F} ,则应在relative layout显示ABCDEF 如果我不使用LayoutParams pramas那么所有textViews都在互相补充。 我如何才能使它们彼此相邻

for (int i = 0 ; i < values.length ; i++)
      {
        TextView textView = new TextView(this);
        textView.setText(values[i].toString());
        textView.setTextColor(Color.BLACK);
        textView.setClickable(true);
        textView.setId(i);
        textView.setBackgroundDrawable(d);
        textView.setTextSize(24);
        LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        LayoutParams params  = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 50, 0, 0); 
        if (i>0)
        params.addRule(RelativeLayout.RIGHT_OF, i);
        textView.setLayoutParams(param);
        wordsLayout.addView(textView,params);
      }
    }

问题是,当我使用wordsLayout.addView(textView,params); 什么都没有显示

我们的工作代码...

LinearLayout wordsLayout = new LinearLayout(this);
        for (int i = 0 ; i < 5 ; i++)
        {
            TextView textView = new TextView(this);
            textView.setText(String.valueOf(i));
            textView.setTextColor(Color.RED);
            textView.setClickable(true);
            textView.setId(i);
            textView.setBackgroundDrawable(d);
            textView.setTextSize(24);
            LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            LayoutParams params  = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 50, 0, 0); 
            if (i>0)
                params.addRule(RelativeLayout.RIGHT_OF, i);
            textView.setLayoutParams(param);
            wordsLayout.addView(textView,params);
        }

        setContentView(wordsLayout);

我建议将每个Textview放在其自己的Viewgroup中,该Viewgroup环绕Textviews内容大小。 按照您希望所有可见textview的方式将所有Viewgroup彼此并排排列。 并将内部textview-elements设为VISIBLE和GONE,但是您需要显示它们。 我认为这是最不麻烦的方式,它可以确保您的textview顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM