动态添加视图android

时间:2015-07-27 14:56:16

标签: android android-layout

我正在尝试动态地将textview添加到我的活动中,但我能够这样做,但添加的文本视图会在右侧彼此相邻添加,而我想要的是将每个textview放在彼此之下。

这是我的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout);

        for(int x = 0;x < 10; x++){
            LinearLayout layout = new LinearLayout(this);
            TextView tv = new TextView(this);
            tv.setText("Text View "+x);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            layout.addView(tv);
            linearLayout.addView(layout);

        }
    }

主XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout"
        android:orientation="horizontal"></LinearLayout>
</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

你可以这样做:

您必须设置父线性布局方向垂直

您的xml应如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout"
        android:orientation="vertical"></LinearLayout>
</RelativeLayout>

您的Java代码应如下所示:

for(int x = 0;x < 10; x++){
     TextView tv = new TextView(this);
     tv.setText("Text View "+x);
     linearLayout.addView(tv);
}

希望这会对你有所帮助。

答案 1 :(得分:1)

而不是:

layout.setOrientation(LinearLayout.VERTICAL);

对线性布局执行此操作:

$('#iframeId').contents().find('html').html(yourContent);
相关问题