Como migrar uma Activity para um Fragment - Android

Boa Noite.

Estou tentando migrar meu app que funciona ok de uma view simples para o midelo da google com fragments. O setcontentview é diferente no oncreate e não sei como usar as duas views ficando meu layout no home fragmente. Segue o oncreate. Obrigado pela ajuda.
Se eu forçar com o setContentView(R.layout.activity_main); a aplicação funciona mas sem os fragments.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main0);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
            R.id.nav_tools, R.id.nav_share, R.id.nav_send)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);

/*//================================================================================================
setContentView(R.layout.activity_main);
//desabilita teclado al iniciar aplicacion
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
inputStreamTextView = (TextView) findViewById(R.id.inputStreamTextView);
inputStreamTextView.setMovementMethod(new ScrollingMovementMethod());
outputStreamTextView = (TextView) findViewById(R.id.outputStreamTextView);
outputStreamTextView.setMovementMethod(new ScrollingMovementMethod());
editSend = (EditText) findViewById(R.id.editSend);
buttonSend = (Button) findViewById(R.id.buttonSend);
condesc = (ToggleButton) findViewById(R.id.condesc);
fastToast = Toast.makeText(this, “”, Toast.LENGTH_SHORT);
buttonSend.setEnabled(false);

    //--------------------------------------------------------------------------
    button1 = (Button)findViewById(R.id.button1);
    button2 = (Button)findViewById(R.id.button2);
    button3 = (Button)findViewById(R.id.button3);
    button4 = (Button)findViewById(R.id.button4);

Boa noite, a criação de Fragment, como vc viu, é bem diferente de uma activity comum. Olha:

public class SeuNovoFragment extends Fragment {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_seu_novo_fragment, container, false); //antigo setContentView(R.layout.activity_main0);
        //botao = view.findViewById(R.id.botao);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    }
}

Mas pelo o que você está fazendo, as coisas terão que ser separadas. Vc está usando o DrawerLayout, isso tem que ser passado pra uma Activity que será padrão.

Vou mandar um exemplo funcional de uma Activity (com BottomNavigationEx) + Fragment.

Activity:

  • HomeActivity.java
  • activity_home.xml

Fragment:

  • SeuNovoFragment.java
  • fragment_seu_novo.xml

activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F5F7F9"
    tools:context=".HomeActivity">

    <FrameLayout
        android:id="@+id/home_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_nav_ex">

    </FrameLayout>

    <com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx
        android:id="@+id/bottom_nav_ex"
        android:layout_width="match_parent"
        android:layout_height="47dp"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:background="@color/white"
        app:elevation="8dp"
        app:itemTextColor="#8705B8"
        app:itemIconTint="@color/custom_color"
        app:menu="@menu/menu_bottom_nav" />

</RelativeLayout>

menu_bottom_nav.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/social_fragment"
        android:checked="false"
        android:icon="@drawable/home"
        android:title="Feed" />

    <item
        android:id="@+id/home_fragment"
        android:checked="true"
        android:icon="@drawable/search"
        android:title="Explorar" />

    <item
        android:id="@+id/chat_fragment"
        android:checked="false"
        android:icon="@drawable/chat"
        android:title="Chat" />

    <item
        android:id="@+id/profile_fragment"
        android:checked="false"
        android:icon="@drawable/user"
        android:title="Perfil" />

</menu>

preview:
image

HomeActivity.java:

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;

public class HomeActivity extends AppCompatActivity {

    private Context mContext;
    private BottomNavigationViewEx bottomNavigationViewEx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mContext = this;

        bottomBar();
    }

    private void bottomBar() {
        bottomNavigationViewEx = findViewById(R.id.bottom_nav_ex);
        try {
            bottomNavigationViewEx.setOnNavigationItemSelectedListener(navListener);
            getSupportFragmentManager().beginTransaction().replace(R.id.home_frame, new FeedFragment()).commit();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
    }

    private BottomNavigationViewEx.OnNavigationItemSelectedListener navListener = menuItem -> {
        Fragment selectedFragment = null;
        switch (menuItem.getItemId()) {
            case R.id.social_fragment:
                selectedFragment = new SeuNovoFragment();
                break;
            case R.id.home_fragment:
                //selectedFragment = new OutroFragment();
                break;
            case R.id.chat_fragment:
                //selectedFragment = new OutroFragment();
                break;
            case R.id.profile_fragment:
                //selectedFragment = new OutroFragment();
                break;
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.home_frame, selectedFragment).commit();
        return true;
    };
}

fragment_seu_novo.xml

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SeuNovoFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="EU SOU UM FRAGMENTTTTTTTTTTTTTTT"/>

</RelativeLayout>

SeuNovoFragment.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

public class SeuNovoFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.fragment_seu_novo_fragment, container, false); //antigo setContentView(R.layout.activity_main0);
        //botao = view.findViewById(R.id.botao);
        return view;
    }
}

Thank you!.

I did several changes and it is working !
Now i have my app code working under a UI Nav controller menu pretty fine.
Howeverr, i want to swipe the fragments. I´m using the standard sample from google, my codde is running on Home fragment, there is 5 fragments. Also the fragments are beeing destroyed when changin each other.
Can you help me again ? thank you.

are u brazilian???

Vou escrever em português, já que o seu questionamento foi em ptBR mesmo.

Isso acontece porquê o fragment vem montado com alguns métodos. Inicialmente eles não são necessários.

Delete os métodos:

newInstance(String param1, String param2){…}
onButtonPressed(Uri uri){…}
onAttach(Context context){…}
onDetach(){…}
OnFragmentInteractionListener{…}

São métodos de “fábrica”, não há problemas em excluir, e também é apenas um template.

Deixe só esses métodos:

public class YourFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

}

Sim, desculpa kk. É a idade. Ok vou tentar excluindo esses métodos. Abraços

Esses métodos não tem, tem os abaixo:

public class HomeFragment extends Fragment {

private HomeViewModel homeViewModel;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);
    final TextView textView = root.findViewById(R.id.text_home);
    homeViewModel.getText().observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            textView.setText(s);
        }
    });
    return root;
}

}

Ahhhh kkkkkk, clica aqui e verifica o erro então:

image

Os fragments são destruidos ao mudar

Encontrei essas dicas:

É que sem a mensagem de erro fica difícil dizer o porquê exatamente está crashando.

Esse vídeo aqui é muito bom e rápido: