在android中创建动态表

时间:2011-02-16 07:02:09

标签: android tablelayout tablerow layoutparams

我正在尝试从二维字符串数组创建一个表。但是,我厌倦了在代码中创建视图,因此出于某种原因,我的图像永远不可见,我的文本视图不会分成多行,而是会删除文本。

另外,我在我的代码中的每个textview上放了id,当有人点击textview时,我希望我可以使用该ID来识别点击的行。不幸的是情况并非如此。

有没有什么好方法可以识别正确的行?

此致

      for (int current=0; current<cityArr.length; current++) {

      TableRow tr = new TableRow(this);
      tr.setId(100+current);
      tr.setLayoutParams(new LayoutParams(
              LayoutParams.FILL_PARENT,
              LayoutParams.WRAP_CONTENT));   

      TextView labelTV = new TextView(this);
      labelTV.setId(current);
      labelTV.setText(cityArr[current][0]);
      labelTV.setTextColor(Color.BLACK);
      labelTV.setLayoutParams(new LayoutParams(
              LayoutParams.FILL_PARENT,
              LayoutParams.WRAP_CONTENT));
      tr.addView(labelTV);

      ImageView mapView = new ImageView(this);
      mapView.setImageResource(R.drawable.list_icon_map);
      mapView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT, 5));
      tr.addView(mapView);

      tlcity.addView(tr, new TableLayout.LayoutParams(
              LayoutParams.FILL_PARENT,
              LayoutParams.WRAP_CONTENT));
  }

2 个答案:

答案 0 :(得分:5)

public class MainActivity extends Activity  {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ScrollView sv = new ScrollView(this);

        TableLayout ll=new TableLayout(this);
        HorizontalScrollView hsv = new HorizontalScrollView(this);

        for(int i=1;i<30;i++) {
            TableRow tbrow=new TableRow(this);

            for(int j=1;j<=20;j++) {
                TextView tv1=new TextView(this);
                String s1 = Integer.toString(i);
                String s2 = Integer.toString(j);
                String s3 = s1+s2;
                int id = Integer.parseInt(s3);
                tv1.setId(id);

                tv1.setText("Dynamic TextView  no:     "+id);
                tbrow.addView(tv1);
            }
            ll.addView(tbrow);
        }
        hsv.addView(ll);
        sv.addView(hsv);
        setContentView(sv);
    }
}

答案 1 :(得分:1)

哈,结果是使用setID()函数正常工作。只要我将OnClickListener放在正确的组件上......