【问题标题】:FragmentActivity and DrawerLayout?FragmentActivity 和 DrawerLayout?
【发布时间】:2014-12-05 20:30:37
【问题描述】:

我创建了一个 DrawerLayout,它工作正常。这个 DrawerLayout 打开了 Fragments,我没有创建 FragmentActivity 来控制我的 Fragments。

在我的应用程序中,我有一个登录活动,如果登录正常,我将启动活动 DrawerLayout。现在,我需要控制我的片段的“返回”,例如,在某些片段中我需要停止返回设备。

1 - 真的需要创建 FragmentActivity 吗?

2 - 如何在没有 FragmentActivity 的情况下停止片段的返回?

3 - 如果我需要创建 FragmentActivity,如何添加 DrawerLayout ?

XML 抽屉布局

<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>

抽屉布局

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;

        }

登录活动

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);          
        }
    }
}

片段

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)));
    }

}

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    FragmentActivity 真的需要创建吗?如何通过单击按钮打开片段?

    您当前使用的是继承FragmentActivityActionBarActivity,因此您已经拥有FragmentManager。如果您想通过单击按钮打开片段,请在按钮的 OnClickListener 代码中添加类似代码:getSupportFragmentManager().beginTransaction().replace(R.id.view_to_which_attac‌​h_fragment, yourNewFragment).commit()

    如何在没有 FragmentActivity 的情况下停止片段中的“按下后退按钮”事件?

    如果我对您的理解正确,您想要的是“覆盖”后退按钮的功能。基本上,您需要了解对后退按钮按下事件做出反应的不是 Fragment。总是 Activity 做出反应,因为 Activity 包含 Fragment 它可以将按下按钮的事件传播给它们。所以在Activity中实现@Override public void onBackPressed() { \\do something here }。请记住在ActionBarActivity 中执行此操作。 Fragment 没有这样的方法。如果您想在您的Fragment 中以某种方式对按下后退按钮的事件做出反应,那么现在从您的ActionBarActivity 中的onBackPressed() 方法通过getSupportFragmentManager().findFragmentById()getSupportFragmentManager().findFragmentByTag() 获取Fragment 并调用其中的一些公共方法.

    如果我需要创建FragmentActivity,如何添加DrawerLayout?

    只需将带有 DrawerLayout 的布局设置为您的 ActionBarActivity 布局。然后在DrawerLayout 中保留FrameLayout,您将通过FragmentManager 添加您的片段。

    【讨论】:

      【解决方案2】:

      FragmentActivity 真的需要创建吗?

      是的,它需要被创建。没有 FragmentActivity,您无法创建 Fragment。 FragmentActivity 包含管理 Fragment 的 FragmentManager。 ActionBarActivity 继承自 FragmentActivity。

      如何在没有 FragmentActivity 的情况下停止片段返回?

      你不能。通过 FragmentManager 控制您的 Fragment。

      如果我需要创建FragmentActivity,如何添加DrawerLayout?

      只需将 DrawerLayout 设置为您的 FragmentActivity 布局布局。然后在 DrawerLayout 中保留 FrameLayout,您将通过 FragmentManager 添加片段。

      【讨论】:

      • 但是ActionBarActivity继承自FragmentActivity:Extend Activity classes from ActionBarCompat: ActionBarCompat contains one Activity class which all of your Activity classes should extend: ActionBarActivity. This class itself extends from FragmentActivity so you can continue to use Fragments in your application. There is not a ActionBarCompat Fragment class that you need to extend, so you should continue using android.support.v4.Fragment as the base class for your Fragments.
      • 非常好。所以,我有一个 FragmentActivity :)。但是,如果我想从布局中的按钮打开片段?
      • 如果您想通过单击按钮打开片段,请在按钮的OnClickListener 代码getSupportFragmentManager().beginTransaction().replace(R.id.view_to_which_attach_fragment, yourNewFragment).commit() 中添加类似代码
      • 哇,我做到了,真的很好用!!!但是我有一个屏幕,我想控制设备的“后退”,你知道吗?如果用户按下设备的“返回”按钮屏幕不返回,你能理解吗?
      • 好吧,我试着总结一下:)
      猜你喜欢
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2012-05-15
      • 2013-10-27
      相关资源
      最近更新 更多