【问题标题】:Handling Back button in Parent Activity处理父活动中的后退按钮
【发布时间】:2017-04-02 19:46:48
【问题描述】:

我的主要活动包含 2 个片段:

主活动

public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{

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

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            FragmentOne fragmentOne = new FragmentOne ();

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne ).commit();


        }

    }

此活动最初显示片段一。

Fragment 1 有一个按钮,当点击它时,它会用 Fragment 2 替换它自己。当按钮被点击时,片段一中的界面得到 ​​p>

//Main acitivty has this method which is a a method the interface in fragment one requires
@Override
    public void goToFragmentTwo() {

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //  setSupportActionBar(toolbar);

        // Create fragment and give it an argument specifying the article it should show
         FragmentTwo fragmentTwo = new FragmentTwo ();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, fragmentTwo );
        transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);

        // Commit the transaction
        transaction.commit();
    }

如果 android 后退按钮或工具栏中的后退按钮被调用,片段需要有一个确认对话框,询问您是否确定要离开。如果确定,那么我有第二个活动,称为 HomeActivity(此活动是 MainActivity 的父活动),它需要转到它,或者如果取消它只需要关闭对话框并留在当前片段中。

所以在 MainActivity 中,我覆盖了 onBackPressed 方法,该方法显示:

@覆盖 公共无效 onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                finish();
        }
    });
    builder.show();
}

这段代码我遇到了两个问题:

1) 按工具栏中的后退按钮不会显示对话框 2) 对话框的 OK 和 Cancel 功能无法正常工作。

基本上我想要完成的是我有一个 HomeActivity,它有一个导航到 MainActivity 的按钮。当 MainActivity 被调用时,我将启动一个工作流,其中每个片段都是该工作流的一部分。如果按下后退按钮,则需要放弃此工作流程,并且应将用户返回到 HomeActivty。

【问题讨论】:

  • 您是否使用自定义工具栏布局?在片段中?而不是使用活动的工具栏。
  • @rafsanahmad007 我不确定?当我创建活动并使 MainActivity 成为 HomeActivity 的子项时,会自动为我提供一个工具栏。我只是在使用这个工具栏。我的代码中没有实际的工具栏视图。
  • 尝试覆盖 HomeActivity 中的onBackPressed...
  • @rafsanahmad007 我已将其从活动中移出,但根本没有出现任何对话框。

标签: android android-fragments


【解决方案1】:

我假设您正在使用 ActionBar。

尝试将其添加到您的活动中:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return false;
}

 @Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    });
    builder.show();
}

【讨论】:

    【解决方案2】:

    1) 您应该让您的工具栏后退按钮从您的活动中调用 onBackPressed(),以便它们共享相同的功能。

    请参阅主活动中的 onSupportNavegationUp()。

    2) 让您的 Main Activity 控制片段发生的情况,但如果必须,让片段处理任何后压。

    希望对你有用。

    清单

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.johnurrutia.so_43172788">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

    activity_main.xml

    <?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"
        tools:context="com.johnurrutia.so_43172788.MainActivity">
    
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolBar"
            android:layout_width="0dp"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">
    
        </android.support.v7.widget.Toolbar>
    
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintTop_toBottomOf="@id/toolBar"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            tools:layout_editor_absoluteY="8dp">
    
        </FrameLayout>
    
    </android.support.constraint.ConstraintLayout>
    

    fragment_one.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <Button
            android:id="@+id/btnGoFrag2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go To Fragment TWO" />
    </LinearLayout>
    

    fragment_two.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <Button
            android:id="@+id/goToFragmentOne"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Go To Fragment One" />
    </LinearLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity
            implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener {
    
        public static final int FRAGMENT_ONE = 0;
        public static final int FRAGMENT_TWO = 1;
    
        private Toolbar toolbar;
        private FragmentOne fragmentOne;
        private FragmentTwo fragmentTwo;
    
        private ArrayList<Fragment> fragments = new ArrayList<>();
        private int currentFragment = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            toolbar = (Toolbar) findViewById(R.id.toolBar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    
            // Check that the activity is using the layout version with
            // the fragment_container FrameLayout
            if (findViewById(R.id.fragment_container) != null) {
    
                // However, if we're being restored from a previous state,
                // then we don't need to do anything and should return or else
                // we could end up with overlapping fragments.
                if (savedInstanceState != null) {
                    return;
                }
    
                // Create a new Fragment to be placed in the activity layout
                fragmentOne = new FragmentOne();
                fragmentTwo = new FragmentTwo();
                fragments.add(FRAGMENT_ONE, fragmentOne);
                fragments.add(FRAGMENT_TWO, fragmentTwo);
    
                // Add the fragment to the 'fragment_container' FrameLayout
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, fragmentOne,"FRAGMENT_ONE")
                        .add(R.id.fragment_container, fragmentTwo, "FRAGMENT_TWO")
                        .hide(fragmentTwo)
                        .show(fragmentOne)
                        .commit();
            }
    
        }
    
    
    
        @Override
        public boolean onSupportNavigateUp() {
            onBackPressed();
            return true;
        }
    
        @Override
        public void onBackPressed() {
            boolean fragmentProcessedTheEvent = ( (BackButtonListener) fragments.get(currentFragment)).onBackPressed();
            if(!fragmentProcessedTheEvent) {
                //The event is for Main Activity to exit
                showActivityExitDialog();
            }
        }
    
        public void showActivityExitDialog() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to leave? ");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    
        private void switchToFragment(int pos) {
            if (currentFragment != pos) {
                getSupportFragmentManager().beginTransaction()
                        .hide(fragments.get(currentFragment))
                        .show(fragments.get(pos))
                        .commit();
                currentFragment = pos;
            }
        }
    
        public void goToFragmentTwo(){
            switchToFragment(FRAGMENT_TWO);
        }
    
        public void goToFragmentOne(){
            switchToFragment(FRAGMENT_ONE);
        }
    }
    

    FragmentOne.java

    public class FragmentOne extends Fragment implements BackButtonListener{
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_one, container, false);
    
            Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.btnGoFrag2);
            goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ( (OnFragmentOneInteractionListener) getActivity() ).goToFragmentTwo();
                }
            });
    
            return v;
        }
    
        public interface OnFragmentOneInteractionListener{
            public void goToFragmentTwo();
        }
    
        @Override
        public boolean onBackPressed() {
            /*
            *  if(fragment_has_any_use_for_back_press){
            *      process_it_here();
            *      return EVENT_PROCESSED;
            *  }
            *
            * */
    
            return EVENT_IGNORED;
        }
    }
    

    FragmentTwo.java

    public class FragmentTwo extends Fragment implements BackButtonListener{
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_two, container, false);
    
            Button goToFragmentTwoBtn = (Button) v.findViewById(R.id.goToFragmentOne);
            goToFragmentTwoBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ( (FragmentTwo.OnFragmentTwoInteractionListener) getActivity() ).goToFragmentOne();
                }
            });
    
            return v;
        }
    
        @Override
        public boolean onBackPressed() {
            /*
            *  if(fragment_has_any_use_for_back_press){
            *      process_it_here();
            *      return EVENT_PROCESSED;
            *  }
            *
            * */
    
            return EVENT_IGNORED;
        }
    
    
        public interface OnFragmentTwoInteractionListener{
            public void goToFragmentOne();
        }
    }
    

    BackButtonListener.java

    public interface BackButtonListener {
        public static final boolean EVENT_PROCESSED = true;
        public static final boolean EVENT_IGNORED = false;
        public boolean onBackPressed();
    }
    

    【讨论】:

    • 感谢您的回复。我对android很陌生,有一些问题。 1)我在哪里或如何让工具栏调用这个方法? 2)如何将活动的 onBackPressed 方法的调用转发到 Fragment(调用哪个方法)?
    猜你喜欢
    • 2011-07-15
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多