将TextView创建在代码中,在TextView的XML下

时间:2011-04-07 17:20:01

标签: android dynamic textview

我已经搜索过高低,但无法使其工作。

            TextView topic = (TextView) findViewById(R.id.topic);
        topic.setText(json_data.getString("topic"));


        TextView poster = (TextView) findViewById(R.id.poster);
        poster.setText(json_data.getString("name"));

        TextView detail = (TextView) findViewById(R.id.detail);
        detail.setText(json_data.getString("detail"));

        TextView test = new TextView(this);
        test.setText("test string");
        test.setTextColor(this.getResources().getColor(R.color.red));

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        p.addRule(RelativeLayout.BELOW, R.id.detail);

        addContentView(test, p);

一切正常,除了最后一个只显示在左上角的textview(测试)。我希望它在textview(详细信息)下。 XML基于            

suedo代码。

任何帮助都会非常感激,因为这是我应用的最后一点。

1 个答案:

答案 0 :(得分:0)

尝试使用test.setLayoutParams(p);

    RelativeLayout yourLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.newlayout, null, false);

    setContentView(yourLayout);

    TextView topic = (TextView) findViewById(R.id.topic);
    topic.setText(json_data.getString("topic"));


    TextView poster = (TextView) findViewById(R.id.poster);
    poster.setText(json_data.getString("name"));

    TextView detail = (TextView) findViewById(R.id.detail);
    detail.setText(json_data.getString("detail"));

    TextView test = new TextView(this);
    test.setText("test string");

    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    p.addRule(RelativeLayout.BELOW, R.id.detail);

    test.setLayoutParams(p);

    yourLayout.addView(test);

    setContentView(yourLayout);