web-dev-qa-db-fra.com

Comment gonfler la vue à l'intérieur du fragment

Si j'essaie de gonfler une vue dans un fragment, j'obtiens NULL. Par exemple:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Here I will inflate my view using the layout ID & return.
    return view;
}

Chaque fois que vous cliquez sur un bouton, je dois créer une vue dynamique, par exemple un bouton & ajouter à LinearLayout. Je voudrais effectuer cette opération dans ma classe de fragment comme ceci:

public void addPlaces() {    
    Button button = new Button(null);
    button.setText("button name");
    // e.g. like adding button to enter code here linear layout
    linearLayout.addView(button); 
}

Donc, si je dois gonfler LinearLayout à l'intérieur de onCreateView et l'utiliser en add class, j'obtiens NULL. Comment y arriver?

39
Naruto

Déclarez la variable en tant que variable d'instance, puis initialisez la présentation linéaire.

LinearLayout linearLayout;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    return rootView;
}

Ensuite

public void addPlaces() {
    Button button = new Button(getActivity());
    // needs activity context
    // fragment hosted by a activity. use getActivity() to get the context of the hosting activity. 
    button.setText("button name");
    linearlayout.addView(button);
}

Exemple: Modifiez le ci-dessous en fonction de vos besoins.

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent" >

    <Button
        Android:id="@+id/button1"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_alignParentBottom="true"
        Android:layout_centerHorizontal="true"
        Android:text="Button" />

    <LinearLayout
        Android:layout_width="fill_parent"
        Android:id="@+id/linearlayout"
        Android:layout_height="fill_parent"
        Android:layout_above="@+id/button1"
        Android:layout_alignParentTop="true"
        Android:layout_centerHorizontal="true"
        Android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

Myfragment.Java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                addPlaces();
            }

        });
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}

Instantané de mon émulateur

enter image description here

Modifier :

activity-main.xml

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <fragment Android:name="com.example.fragments.Myfragment"
            Android:id="@+id/frag"
            Android:layout_above="@+id/button1"
            Android:layout_width="fill_parent"
            Android:layout_height="fill_parent" />

      <Button
          Android:id="@+id/button1"
          Android:layout_width="wrap_content"
          Android:layout_height="wrap_content"
          Android:layout_alignParentBottom="true"
          Android:layout_centerHorizontal="true"
          Android:text="Button" />

</RelativeLayout>

MainActivity.Java

public class MainActivity extends FragmentActivity {
    Button b;
    Myfragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragment = new Myfragment();
        fragmentTransaction.add(R.id.frag, fragment);
        fragmentTransaction.commit();
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.addPlaces();
            }

        });
    }
}

Myfragment.Java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}
66
Raghunandan