3

Tenho um app com uma tela e nessa tela há um fragment. Nesse fragment há um botão que, quando clicado, quero chamar outro fragment e que fique/substitua o fragment do botão. Tenho tentando algumas coisa que vi, na web e não estou conseguindo.

Tela RecargaActivity

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.gustavo.easypasse.RecargaActivity"
tools:showIn="@layout/activity_recarga">

<LinearLayout
    android:id="@+id/linearLayout11"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:background="@android:color/black"
    android:orientation="horizontal"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Valor da recarga"
        android:textColor="@android:color/background_light" />

    <EditText
        android:id="@+id/edtValorRecarga"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_dark"
        android:ems="10"
        android:inputType="textPersonName" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout12"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:background="@android:color/black"
    android:orientation="horizontal"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout11">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="CPF"
        android:textColor="@android:color/background_light" />

    <EditText
        android:id="@+id/edtCPF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="9dp"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_dark"
        android:ems="10"
        android:inputType="textPersonName" />
</LinearLayout>

<LinearLayout
    android:id="@+id/llContainer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/black"
    android:orientation="horizontal"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout12">

    <include
        android:id="@+id/includeCartaoCreditoDebito"
        layout="@layout/fragment_cartao_boleto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout8"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="168dp"
    android:orientation="horizontal"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/llContainer">

    <TextView
        android:id="@+id/textView10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Saldo disponível"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

    <TextView
        android:id="@+id/textView11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Saldo gasto"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />
</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="35dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:orientation="horizontal"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout8"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:id="@+id/linearLayout9">

    <TextView
        android:id="@+id/tvValorSaldoDisponivel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="R$ 850,00"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tvValorSaldoGasto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="R$ 125,00"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout10"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="12dp"
    android:orientation="horizontal"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout9">

    <TextView
        android:id="@+id/textView14"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Data renovar recarga"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

    <TextView
        android:id="@+id/textView15"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Transferência de saldo"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout15"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout10"
    app:layout_constraintVertical_bias="0.0">

    <TextView
        android:id="@+id/tvDataRenovarRecarga"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="18/10/2017"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tvValorTransSaldo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="-R$ 25,00"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp" />
</LinearLayout>

1º fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gustavo.easypasse.CartaoBoletoFragment">

<!-- TODO: Update blank fragment layout -->
<LinearLayout
    android:id="@+id/linearLayout13"
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:layout_marginEnd="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_marginStart="0dp"
    android:layout_marginTop="0dp"
    android:background="@android:color/black"
    android:orientation="horizontal"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout12">

    <TextView
        android:id="@+id/textView9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="FORMA DE PAGAMENTO"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout14"
    android:layout_width="wrap_content"
    android:layout_height="25dp"
    android:layout_marginTop="25dp"
    android:background="@android:color/black"
    android:orientation="horizontal"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout13">

    <TextView
        android:id="@+id/textView13"
        android:layout_width="225dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.98"
        android:text="Cartão de crédito/débito"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

    <TextView
        android:id="@+id/textView16"
        android:layout_width="230dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Boleto bancário"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

</LinearLayout>

<LinearLayout
    android:id="@+id/LinearLayoutCartaoBoleto"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginTop="50dp"
    android:background="@android:color/black"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/ibCartaoCredito"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/black"
        android:onClick="cartaoCreditoDebito"
        android:src="@drawable/cartao_de_credito_01" />

    <ImageButton
        android:id="@+id/ibBoleto"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/black"
        android:src="@drawable/boleto_bancario_01" />
</LinearLayout>

2º fragment

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment_cartao"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gustavo.easypasse.CartaoCreditoFragment">

<!-- TODO: Update blank fragment layout -->

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView12"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:background="@android:color/black"
        android:text="FORMA DE PAGAMENTO"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

    <TextView
        android:id="@+id/textView18"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@android:color/black"
        android:text="Cartão de Crédito/Débito"
        android:textAlignment="center"
        android:textColor="@android:color/background_light" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:src="@drawable/cartao_de_credito_01" />

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="140dp"
    android:orientation="vertical">

</LinearLayout>

Activity da tela Recarga

public class RecargaActivity extends AppCompatActivity {

private EditText valorRecarga;
private EditText cpf;
private ImageButton boleto;
private TextView saldoDisponivel;
private TextView saldoGasto;
private TextView renovarRecarga;
private TextView transSaldo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recarga);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    valorRecarga = (EditText) findViewById(R.id.edtValorRecarga);
    cpf = (EditText) findViewById(R.id.edtCpf);

    saldoDisponivel = (TextView) findViewById(R.id.tvValorSaldoDisponivel);
    saldoGasto = (TextView) findViewById(R.id.tvValorSaldoGasto);
    renovarRecarga = (TextView) findViewById(R.id.tvDataRenovarRecarga);
    transSaldo = (TextView) findViewById(R.id.tvValorTransSaldo);

}

}

Activity do fragment chamado

public class CartaoCreditoFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public CartaoCreditoFragment() {
    // Required empty public constructor
}

// TODO: Rename and change types and number of parameters
public static CartaoCreditoFragment newInstance(String param1, String param2) {
    CartaoCreditoFragment fragment = new CartaoCreditoFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_cartao_credito, container, false);

    final ImageButton cartaoCreditoDebito = (ImageButton) v.findViewById(R.id.ibCartaoCredito);

    cartaoCreditoDebito.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            CartaoCreditoFragment cartaoCreditoFragment =  new CartaoCreditoFragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction()
                    //.replace(R.id.llContainer, new CartaoCreditoFragment()).commit();
                    .replace(R.id.includeCartaoCreditoDebito, new CartaoCreditoFragment()).commit();
        }
    });

    return v;

}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

}

}

2
  • Não serve usar uma Tabbed Activity?
    – Costamilam
    Commented 14/11/2017 às 21:46
  • Não sei é possível mudar de fragmento para fragmento mas creio que isso não é uma boa prática. Uma sugestão seria em seu XML, do fragmento, chamar uma função que está na view principal RecargaActivity algo como public void didClickChangeCard(View view) e nessa função você deveria trocar de fragmento afinal a atividade, Activity, que deveria ter essa responsabilidade de gerenciar a view. Commented 28/09/2019 às 16:13

2 Respostas 2

1

É muito simples!

Dentro do método "onClick" do botão que serve para chamar outro fragmento faça o seguinte:

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

FrgmentTransaction fragmentTransaction = fragmentManager.beginTransacition();

fragmentTransaction.replace(R.id.fragmentContainer, new Fragment2()).commit();

Observe que "R.id.fragmentContainer" é o nome do frameLayout que está contido no seu arquivo xlm e que contém seus fragmentos e "Fragment2()" é a classe do novo fragmento que você quer iniciar.

Espero que isso te ajude. Boa sorte!

0
  1. Sua Activity deve possuir um <fragment>:
      <fragment
         android:id="@+id/
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
  1. Tente da seguinte forma:
/**
 * Informe a Activity onde está localizado o fragmnet container, 
 * O Fragment que será exibido.
 * O nome da Fragment
 **/
    public static final void abrir(final SuaActivity mActivity, final Fragment mFragment, final String name) {
        if (null == mActivity || null == mFragment) {
            return;
        }
        final FragmentManager _manager = mActivity.getFragmentManager();
        final FragmentTransaction _transaction = _manager.beginTransaction();
        _transaction.add(R.id.container, mFragment, name);
        /**
         * Adiciona à pilha!
         * Isso significa que a transação será lembrada depois que ela for comprometida e irá reverter sua operação quando mais tarde sair da pilha.
         */
        _transaction.addToBackStack(name);
    }
4
  • Que jeito terrível essa 2a. opção kkkkk Commented 7/12/2017 às 19:25
  • Por que acha terrível? Podes comentar / responder a respeito? Desta forma podemos trocar experiências e pontos de vista ! Assim todos nós aprendemos juntos, sendo este o objetivo deste site! =) Commented 8/12/2017 às 16:11
  • @ThiagoLuizDomacoski a primeira opção não cria um fragmento estático que não pode ser substituído por código? Commented 25/12/2018 às 16:18
  • Sua função estática ta dentro do fragmento ou da atividade ? Essa sua resposta leva em consideração que todos os fragmentos são carregados com static de uma vez na tela ? Commented 28/09/2019 às 16:20

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .