FernandoPaiva
FernandoPaiva

Reputation: 4460

FragmentActivity and DrawerLayout?

I created a DrawerLayout, it's works fine. This DrawerLayout open the Fragments and I did not create FragmentActivity to control my Fragments.

In my App I have an Activity that do Login, if login is ok I'm start activity DrawerLayout. Now, I need control "back" of my Fragments, for example, in some fragments I need stop go back of device.

1 - The FragmentActivity really need to be created ?

2 - How can I stop back of fragment withou FragmentActivity ?

3 - If I need create FragmentActivity, how can I add the DrawerLayout ?

XML DrawerLayout

<android.support.v4.widget.DrawerLayout
    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:id="@+id/dl"
     >

   <FrameLayout 
       android:id="@+id/fl"
       android:layout_width="match_parent"
       android:layout_height="match_parent"       
       >       
   </FrameLayout>

   <ListView
       android:id="@+id/lv"
       android:layout_width="250dp"
       android:layout_height="match_parent"
       android:choiceMode="singleChoice"
        android:divider="#e9ba68"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:dividerHeight="1dp"
        android:background="#ac453c"
        android:layout_gravity="start"
       >

   </ListView>

</android.support.v4.widget.DrawerLayout>

DrawerLayout

public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
    private ActionBar ab;
    private DrawerLayout dl;
    private ListView lv;
    private ActionBarDrawerToggle tg;

    private List<ItensListView> fragments;
    private CharSequence tl; //titulo principal
    private CharSequence tlf; //titulo fragment 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_drawerlayout);  
        init();

        if(savedInstanceState == null){
            selectedItem(0);
        }
    }

    private void init(){
        //actionbar
        onConfigActionBar();
        //listview
        configItensListView();
        lv = (ListView)findViewById(R.id.lv);               
        lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
        lv.setOnItemClickListener(this);        
        //drawerlayout
        dl = (DrawerLayout)findViewById(R.id.dl);
        //actionbardrawertoggle
        tg = new ActionBarDrawerToggle(this, dl, R.drawable.btmenu, R.string.nomeActionBar){
            public void onDrawerClosed(View view) {
                ab.setTitle(tl);                
                supportInvalidateOptionsMenu();
            }

            public void onDrawerOpened(View view) {
                ab.setTitle(tlf);
                supportInvalidateOptionsMenu();
            }
        };      
        dl.setDrawerListener(tg);

        tl = tlf = getTitle();      
    }

    /** ativa actionbar e botao home na action bar */
    private void onConfigActionBar(){
        ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        tg.onConfigurationChanged(newConfig);
    }

    /** necessario */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        tg.syncState();
    }

    /** necessario */
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {           
        if (tg.onOptionsItemSelected(item)) {
            return true;
        }            
        return super.onOptionsItemSelected(item);
     }


     /** necessario */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
        return true;
    }

    /** necessario */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean status = dl.isDrawerOpen(lv);
        menu.findItem(R.id.action_settings).setVisible(!status);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
        selectedItem(position);     
    }

    /** open fragments */
    private void selectedItem(int position){
        FragmentTransaction ft;
        Fragment frag;
        switch(position){
            case 0:
                //frag = new InicioFrag();
                frag = new InicioFrag();
                ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack("back");
                ft.commit();
                break;
            case 1:
                frag = new ApresentacaoFrag();
                ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack("back");
                ft.commit();
                break;
            case 3:
                frag = new PerfilFrag();
                ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack("back");
                ft.commit();
                break;

        }

Login Activity

public class LoginView extends Activity implements OnClickListener{
    private EditText etEmail;
    private EditText etSenha;
    private Button btCadastrar;
    private Button btEntrar;
    private Button btEsqueci;
    private Intent intentCadastrar;
    private Intent intentEsqueci;
    private Intent intentInicio;
    private ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove barra de titulos
        setContentView(R.layout.login);

    private void doLogin(){
        if(etEmail.getText().toString().isEmpty() || etSenha.getText().toString().isEmpty()){
            Toast.makeText(this, "Informe todos os campos", Toast.LENGTH_SHORT).show();
        }else{
            progress = new CustomProgressDialog().getCustomProgress(null, LoginView.this);
            progress.show();

            Usuario usuario = new Usuario();
            usuario.setEmail(etEmail.getText().toString());
            usuario.setSenha(etSenha.getText().toString());
            ApplicationController app = new UsuarioDAO().isUsuarioLogin(
                                                        usuario, 
                                                        new UsuarioAdapter(){
                                                            @Override
                                                            public void usuarioIsLogin(Boolean result) {
                                                                if(!result){
                                                                    Toast.makeText(getApplicationContext(), "Email ou senha inválido", Toast.LENGTH_SHORT).show();;
                                                                }else{                                                                  
                                                                    startActivity(new Intent(getApplicationContext(), CustomDrawerLayout.class));
                                                                    finish();
                                                                }
                                                                progress.dismiss();
                                                        }

            });
            CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);          
        }
    }
}

Fragment

public class ApresentacaoFrag extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.apresentacao_view, container, false); 

        TextView txtView = (TextView)view.findViewById(R.id.tvApresentacao);
        txtView.setText(Html.fromHtml(getString(R.string.apresentacao)));

        return  view;
    }

    private void alteraTextView(String texto){
        TextView txtView = (TextView)getView().findViewById(R.id.tvApresentacao);
        txtView.setText(Html.fromHtml(getString(R.string.apresentacao)));
    }

}

Upvotes: 0

Views: 865

Answers (2)

michal.z
michal.z

Reputation: 2075

The FragmentActivity really need to be created? How can I open fragment by clicking a button?

You're currently using ActionBarActivity which inherits FragmentActivity, so you already have FragmentManager. If you want to open fragment by clicking a button then add similar code in button's OnClickListener code: getSupportFragmentManager().beginTransaction().replace(R.id.view_to_which_attac‌​h_fragment, yourNewFragment).commit()

How can I stop 'back button pressed' event in fragment without FragmentActivity?

If I understand you correctly what you want is to 'override' the functionality of back button. Basically you need to understand that it is not Fragment who react to back button pressed event. It is always Activity who react and because Activity contains Fragment it can propagate back button pressed event to them. So implement @Override public void onBackPressed() { \\do something here } in Activity. Remember to do that in ActionBarActivity. Fragment doesn't have such a method. If you want to react in some way in your Fragment for back button pressed event then now from onBackPressed() method in your ActionBarActivity get a Fragment by getSupportFragmentManager().findFragmentById() or getSupportFragmentManager().findFragmentByTag() and call some of it's public methods.

If I need create FragmentActivity, how can I add the DrawerLayout?

Simply set layout with DrawerLayout inside as your ActionBarActivity layout. Then inside that DrawerLayout keep FrameLayout to which you will add your fragments through FragmentManager.

Upvotes: 1

michal.z
michal.z

Reputation: 2075

The FragmentActivity really need to be created ?

Yes, it need to be created. You cannot create Fragments without FragmentActivity. FragmentActivity contains FragmentManager which manages Fragments. ActionBarActivity inherits from FragmentActivity.

How can I stop back of fragment without FragmentActivity ?

You can not. Control your Fragments through FragmentManager.

If I need create FragmentActivity, how can I add the DrawerLayout?

Simply set as your FragmentActivity layout layout with DrawerLayout inside. Then inside that DrawerLayout keep FrameLayout to which you will add your fragments through FragmentManager.

Upvotes: 0

Related Questions