Click here to Skip to main content
15,309,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have a Fragment, and i want to add elements (textview, button) dynamically when i click on Floating Action Button.

What I have tried:

Code:
Java
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this 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;
    }


Thanks in Advanced:)
Posted
Updated 15-Jul-16 22:12pm

1 solution

The following sample adds a new LinearLayout and then adds two TextView objects to that, all within an existing LinearLayout.
Java
private void ShowDetail() {
    final int[] idList = { R.string.lblOne, R.string.lblTwo, R.string.lblThree, R.string.lblFour }; 
    LinearLayout llv = (LinearLayout)findViewById(R.id.llvDetail);
    setTitle("item.toString()");
    for (int id : idList) {
    // Create LinearLayout
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    
    // Create TextView for the item label
    TextView txtLabel = new TextView(this);
    txtLabel.setText(getString(id) + ": ");
    txtLabel.setWidth((int)getResources().getDimension(R.dimen.activity_label_width));
    txtLabel.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
    //		txtLabel.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);
    ll.addView(txtLabel);
    
    // Create TextView for the item content
    TextView txtContent = new TextView(this);
    txtContent.setText(getString(id));
    txtContent.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);
    //		txtLabel.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
    ll.addView(txtContent);
    //Add button to LinearLayout defined in XML
    llv.addView(ll);
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900