How to dynamically add a layout ?

2019-06-14 12:25发布

Here is my xml

<TextView android:id="@+id/itemNameTextView"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textColor="#000000" android:textSize="30sp" 
    android:layout_centerVertical="true" android:drawableLeft="@drawable/doller"
    android:drawablePadding="30dp" android:layout_marginLeft="30dp"/>

<Button android:id="@+id/buttonAdd"
    android:layout_width="wrap_content" android:layout_height="fill_parent"
    android:textColor="#000000" android:background="#00000000"
    android:layout_alignParentRight="true" android:layout_marginRight="10dp"
    android:text="ADD" android:textSize="25sp" android:textStyle="bold" />

<EditText android:id="@+id/displayPriceEditText"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#000000" android:textSize="30sp" android:hint="0.00"
    android:layout_centerVertical="true" android:layout_toLeftOf="@id/buttonAdd"
    android:layout_marginRight="40dp" android:background="#00000000"/>

I should be able to add some text both in editText and textView and when i click the button the same layout has to appear just below this one( like a list ). Can anyone please help me on this?

3条回答
太酷不给撩
2楼-- · 2019-06-14 12:52

have two XMl files... the row (row.xml)or what ever reusable stuff you want to add as one view is one and the view to which it needs to be added to is another listbased.xml... in the second one have a button and all the other stuff that needs to go in.... Make sure that you have a parent view inside the listbased.xml(relative,linear,listview).... or something like that...

now... in the class... where this method needs to be called set the R.setContentView(r.layout.listbased).... and

where you implement a button listener then add an inflater (ex:parentLayout.addView(mInflater.inflate(R.layout.row)))... where

public LayoutInflater mInflater; is defined as a global...

查看更多
我命由我不由天
3楼-- · 2019-06-14 12:55

Parent should be a linearLayout . then add by

LinearLayout parentLayout = (LinearLayout) findViewById(id);

parentLayout.addView(childView)
查看更多
地球回转人心会变
4楼-- · 2019-06-14 13:13

You have to create similar layout at runtime.and then you can add the whole layout to this view.

For that,you have to have a LinearLayout/RelativeLayout object in your code,also you would have to create EditText,Button and TextView programatically,setting up their properties as you require and then can add all components to your LinearLayout/RelativeLayout object.

And then you can add that object to your main layout.

Yes,you need to have Layout object of your xml file,then only,you can add above object to it.

查看更多
登录 后发表回答