Estoy haciendo una práctica con Fragments.
Solo hay una actividad con un LinearLayout vertical. Al ejecutar la App se carga un fragmento con un TextView que se podrá modificar usando los botones que contiene un segundo fragmento. En principio aparecen dos botones: Change text y Reset Text. Hasta aquí funciona.
Al pulsar el primer botón, se cambia el texto original del TextView , el segundo botón lo restaura. Además el primer botón debe sustituir el fragmento donde están los botones por otro que agrega un tercer botón: Erase text. Este fragmento, con tres botones, debe sustituir al original, con dos botones, pero se superpone. Es decir, en la actividad, siguen estando los dos botones originales y debajo vuelven a aparecer junto al tercero. Los botones del nuevo fragmento no son funcionales... Intente aplicar esta solución, es decir incluir en el layout principal el fragment dentro de un FragmentLayout que lleva su id: error que no deja cargar la app. No me van los emuladores y uso para depurar un dispositivo real con Android 4.1, la App usa API level 16.
Clases:
MainActivity.java
package com.example.orici.fragmentsdinamicos;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private boolean flag = false;
final private FragmentManager fm = getFragmentManager();
private FragmentTransaction ft = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main );
final TextView label = (TextView) findViewById( R.id.label );
final Button btn_change = (Button) findViewById( R.id.btn1 );
final Button btn_reset = (Button) findViewById( R.id.btn2 );
final Button btn_erase = (Button) findViewById( R.id.btn3 );
btn_change.setOnClickListener( new View.OnClickListener() {
public void onClick( View v ) {
label.setText( R.string.text2 );
changeFrBtns();
}
});
btn_reset.setOnClickListener( new View.OnClickListener() {
public void onClick( View v ) {
label.setText( R.string.text1 );
}
});
if ( flag ) {
btn_erase.setOnClickListener( new View.OnClickListener() {
public void onClick( View v ) {
label.setText( "" );
}
});
} //flag
}
private void changeFrBtns() {
//Acciones para mostrar el fragment fr_btns2
flag = true;
ft = fm.beginTransaction();
ft.replace(
R.id.place_btns,
new FragmentBtns2()
);
ft.addToBackStack( null );
ft.commit();
}
private void resetFrBtns() {
//Acciones para mostrar el fragment fr_btns2
flag = true;
ft = fm.beginTransaction();
ft.replace(
R.id.place_btns,
new FragmentBtns1()
);
ft.addToBackStack( null );
ft.commit();
}
} //class
FragmentBtns1.java
Carga fragmento al inicio con botones
package com.example.orici.fragmentsdinamicos;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Incluye fragmento con los botones en la actividad
*
*/
public class FragmentBtns1 extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
try {
Log.d( "@", "Inflating the layout for buttons fragment..." );
return inflater.inflate( R.layout.fr_btns1, container, false );
} catch ( InflateException e ) {
Log.e( "@Err", e.getMessage( ));
}
return null;
}
} //class
FragmentBtns2.java
Carga fragmento dinámicamente con botones
package com.example.orici.fragmentsdinamicos;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentBtns2 extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
try {
Log.d( "@@@", "Inflating the layout for bottom fragment..." );
return inflater.inflate( R.layout.fr_btns2, container, false );
} catch ( InflateException e ) {
Log.e( "@Err", e.getMessage( ));
}
return null;
}
} //class
FragmentLabel.java
Carga fragmento con TextView al inicio
package com.example.orici.fragmentsdinamicos;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Trace;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Incluye fragmento con TextView en la actividad
*
*/
public class FragmentLabel extends Fragment {
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
try {
Log.d( "@", "Inflating the layout for label fragment..." );
return inflater.inflate( R.layout.fr_label, container, false );
} catch ( InflateException e ) {
Log.e( "@Err", e.getMessage( ));
}
return null;
}
} //class
Ficheros XML
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_vertical_margin"
tools:context="com.example.orici.fragmentsdinamicos.MainActivity">
<!--/ Fragmento con el texto /-->
<fragment android:name="com.example.orici.fragmentsdinamicos.FragmentLabel"
android:id="@+id/fr_label"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--/ Fragmento con los botones /-->
<!--/ Fragmento dinámico /-->
<FragmentLayout
android:id="@+id/place_btns"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<fragment android:name="com.example.orici.fragmentsdinamicos.FragmentBtns1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FragmentLayout>
</LinearLayout>
res/layout/fr_btns1.xml
fragment con botones que se carga al inicio
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fr_btns1" >
<Button
android:text="@string/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="@+id/btn1" />
<Button
android:text="@string/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="@+id/btn2" />
</LinearLayout>
res/layout/fr_btns2.xml
fragment con botones que se carga dinámicamente
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@android:color/darker_gray"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fr_btns2" >
<Button
android:text="@string/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="@+id/btn1" />
<Button
android:text="@string/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="@+id/btn2" />
<!-- nuevo botón. No aparece al cargar la App -->
<Button
android:text="@string/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="@+id/btn3" />
</LinearLayout>
res/layout/fr_label.xml
fragment con TextView que se carga al inicio
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="@string/text1"
android:id="@+id/label" />
</LinearLayout>
res/values/strings.xml
<resources>
<string name="app_name">FragmentsDinamicos</string>
<string name="text1">Hola Mundo!</string>
<string name="text2">Lorem ipsum lorem</string>
<string name="btn1">Change text</string>
<string name="btn2">Reset text</string>
<string name="btn3">Erase text</string>
</resources>