How to dynamically add a layout ?

馋奶兔 提交于 2019-12-12 10:18:15

问题


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?


回答1:


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...




回答2:


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.




回答3:


Parent should be a linearLayout . then add by

LinearLayout parentLayout = (LinearLayout) findViewById(id);

parentLayout.addView(childView)


来源:https://stackoverflow.com/questions/7977071/how-to-dynamically-add-a-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!