How to add elements dynamically in fragment in android -
i have fragment, , want add elements (textview, button) dynamically when click on floating action button.
code:
@override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // inflate layout fragment view view = inflater.inflate(r.layout.xyz, container, false); floatingactionbutton fab = (floatingactionbutton) view.findviewbyid(r.id.fab); fab.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { // new elements on click // new elements on click } }); return view; }
try xml code fragment
<?xml version="1.0" encoding="utf-8"?> <framelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <linearlayout android:id="@+id/linearlayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"/> <android.support.design.widget.floatingactionbutton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="10dp" app:srccompat="@android:drawable/ic_dialog_email"/> </framelayout>
and java code fragment
package com.example.androiddeveloper.fragmentdynamic; import android.os.bundle; import android.support.annotation.nullable; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v4.app.fragment; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.button; import android.widget.linearlayout; /** * simple {@link fragment} subclass. */ public class blankfragment extends fragment { private linearlayout linearlayout = null; public blankfragment() { // required empty public constructor } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // inflate layout fragment return inflater.inflate(r.layout.fragment_blank2, container, false); } @override public void onviewcreated(view view, @nullable bundle savedinstancestate) { super.onviewcreated(view, savedinstancestate); linearlayout = (linearlayout) view.findviewbyid(r.id.linearlayout); floatingactionbutton fab = (floatingactionbutton)view.findviewbyid(r.id.fab); fab.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { //create controls(ui widget, button,textview) , add layout button btn = new button(getactivity()); btn.settext("manual add"); btn.setlayoutparams(new linearlayout.layoutparams(linearlayout.layoutparams.match_parent, linearlayout.layoutparams.wrap_content)); linearlayout.addview(btn); } }); } }
Comments
Post a Comment