How to convert an activity to a fragment in Androi

2019-07-09 20:13发布

I have this activity

package com.padilla.jorge.proyecto_aplicaciones_moviles;


import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Calendar;



public class VerPerfil extends AppCompatActivity {
private String[] arraySpinner;
Intent i;
TextView Nombre_TextView;
TextView Email_TextView;
TextView Password_TextView;
TextView Puntos_TextView;

TextView getNombre;
TextView getEmail;
TextView getPassword;
TextView getPuntos;


ArrayList<TextView> textViewsVal;
ArrayList<TextView> textViewsName;

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference;

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ver_perfil);
    Nombre_TextView=(TextView)findViewById(R.id.Nombre_textView);
    Email_TextView=(TextView)findViewById(R.id.Email_TextView);
    Password_TextView=(TextView)findViewById(R.id.Password_TextView);
    Puntos_TextView=(TextView)findViewById(R.id.Puntos_TextView);
    getNombre=(TextView)findViewById(R.id.Nombre_valor);
    getEmail=(TextView)findViewById(R.id.Email_valor);
    getPassword=(TextView)findViewById(R.id.Password_valor);
    getPuntos=(TextView)findViewById(R.id.Puntos_valor);


    textViewsName = new ArrayList<TextView>();
    textViewsName.add(Nombre_TextView);
    textViewsName.add(Email_TextView);
    textViewsName.add(Password_TextView);
    textViewsName.add(Puntos_TextView);

    textViewsVal = new ArrayList<TextView>();
    textViewsVal.add(getNombre);
    textViewsVal.add(getEmail);
    textViewsVal.add(getPassword);
    textViewsVal.add(getPuntos);
    Intent name_intent=this.getIntent();
    final String name=name_intent.getExtras().getString("name");

    reference = database.getReference(name).child("Perfil");
    reference.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //rutina.setText(dataSnapshot.getKey());
            int i = 0;
            Log.d("number of childs",""+dataSnapshot.getChildrenCount());

            for (DataSnapshot child : dataSnapshot.getChildren()) {

                if (i < 10) {
                    textViewsName.get(i).setText(child.getKey());
                    textViewsVal.get(i).setText(child.getValue().toString());
                    Log.d("User key", child.getKey());
                    Log.d("User ref", child.getRef().toString());
                    Log.d("User val", child.getValue().toString());
                    i++;
                }

            }
        }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


}

}

and i was wondering if there's a simple way to convert it to a fragment? Any help would be appreciated. The reason i want to do this is because i want to implement a navigation drawer menu and i've seen that you have to use fragments (i know there's a way to do it with classes but it's way more complicated) and i already have this class so i would like to reuse it instead of creating a new fragment from scratch.

2条回答
祖国的老花朵
2楼-- · 2019-07-09 20:51

Try this:

  1. Create fragment
  2. Move that code and layout to fragment instead
  3. Now you have a reusable fragment
  4. Add the fragment in your activity or navigation drawer or wherever you like
查看更多
趁早两清
3楼-- · 2019-07-09 20:57

Let's try this:

  1. Extend fragment and refactor MyActivityClass to MyFragmentClass

original: public class MyActivityClass extends AppCompatActivity
converted: public class MyFragmentClass extends Fragment

  1. Create factory method and add all the values that you get from getIntent().getExtra() as parameters for the method

original: String name=getIntent.getExtras().getString("name");

converted:

This

public static MyFragmentClass newInstance(String name){
    MyFragmentClass fragment = new MyActivity();
    Bundle args = new Bundle();
    args.putString(KEY_NAME, name);
    fragment.setArguments(args);
    return fragment;
}

and this,

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        name = getArguments().getString(KEY_NAME);
    }
}
  1. override method onCreateView() and inflate your layout

original: setContentView(R.layout.activity_layout);

converted:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_layout, container, false);
        return view;
    }
  1. place all the findViewById(...); statement in onCreateView() and rename to view.findViewById(...) and other code which does not need the activity to run.

  2. override onActivityCreated() and place all the code that needs Activty in here.

  3. remove code already converted to fragment

It's not the perfect answer but should help.

查看更多
登录 后发表回答