Naruto
Naruto

Reputation: 9634

Add view to layout inside fragment

is it possible to add view to layout inside fragment. My fragment code looks like this, but i m getting crash while adding.

I want to add views dynamically to linear layout inside fragment.

package com.emergreen.goresq;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.SherlockFragment;

public class GRPlacesFragment extends SherlockFragment{

    GRMyPlaces grmp;
    View myview;

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.grpl,
                                         container, false);

            myview = view;
            return view;
        }


     public void addPlaces(context gr)
     {
         grmp = gr;

         LinearLayout ll = (LinearLayout) myview.findViewById(R.id.pid);

         Button button = new Button(grmp);
         button.setText("Testing button");



         ll.addView(button);


     }

}

Upvotes: 1

Views: 1942

Answers (1)

Demitrian
Demitrian

Reputation: 3230

Try doing the following which seems to work for me when I used fragments for a project:

public class GRPlacesFragment extends SherlockFragment {

...
private View myView;

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.grpl, container, false);

        return myView;
    }


 ...

}

Something seems to be amiss in your assignments of your variables, since you change between using "view" and "myview".

You should furthermore ensure that your two variables are private and thereby only accesible to this specific class.

Tell me whether or not this helps.

Upvotes: 1

Related Questions