znl_12 2013-06-17 06:48 采纳率: 0%
浏览 3437
已采纳

在 linear layout 上动态的添加 textviews 数组

我想在linear layout上动态的添加textviews 数组,然后定义为一个公共变量。当我运行程序时,当进入循环语句时程序就强行关闭了。

LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
            LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT,    LayoutParams.WRAP_CONTENT);
            pairs=new TextView[num_match+1];
            for(int l=1;l<=num_match;l++)
            {
                pairs[l].setTextSize(15);
                pairs[l].setLayoutParams(lp);
                pairs[l].setId(l);
                pairs[l].setText(m1[l]+" - "+m2[l]);
                myLayout.addView(pairs[l]);
            }
  • 写回答

2条回答

  • csh_34 2013-06-18 08:30
    关注

    你需要创建新的 TextViews 放入 TextView 数组中,然后就跳到第一个索引中 (pairs[0])。这就是导致错误的原因。

    pairs=new TextView[num_match];
    for(int l=0; l<num_match; l++)
    {
        pairs[l] = new TextView(this);
        pairs[l].setTextSize(15);
        pairs[l].setLayoutParams(lp);
        pairs[l].setId(l);
        pairs[l].setText(m1[l + 1]+" - "+m2[l + 1]);
        myLayout.addView(pairs[l]);
    }
    

    再给你小事例:

    public class Example extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
            LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT,    LayoutParams.WRAP_CONTENT);
            TextView[] pairs=new TextView[4];
            for(int l=0; l<4; l++)
            {
                pairs[l] = new TextView(this);
                pairs[l].setTextSize(15);
                pairs[l].setLayoutParams(lp);
                pairs[l].setId(l);
                pairs[l].setText((l + 1) + ": something");
                myLayout.addView(pairs[l]);
            }
        }
    }
    

    使用布局 main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮