android-fragments 如何检测当按下返回按钮在片段Android?

pod7payv  于 2022-11-13  发布在  Android
关注(0)|答案(7)|浏览(205)

我有项目与导航抽屉与片段,与5菜单,问题是当我去菜单4和我按下后退按钮的应用程序关闭,但我需要的应用程序回到第一个菜单,这是所有的菜单片段。
这是主要活动的代码(导航抽屉)

public class MainActivity extends AppCompatActivity{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /**
     *Setup the DrawerLayout and NavigationView
     */

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

    /**
     * Lets inflate the very first fragment
     * Here , we are inflating the TabFragment as the first Fragment
     */

    mFragmentManager = getSupportFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();
    /**
     * Setup click events on the Navigation View Items.
     */

    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();


            if (menuItem.getItemId() == R.id.nav_item_lux_level_recomen) {
                FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();

            }

            if (menuItem.getItemId() == R.id.nav_item_room_index_calc) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new RoomIndex()).commit();
            }

            if (menuItem.getItemId() == R.id.nav_item_utilization_factor_calc) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new UtilizationFactorCalculator()).commit();
            }

            if (menuItem.getItemId() == R.id.nav_item_conversions) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new Conversion()).commit();
            }
            if (menuItem.getItemId() == R.id.nav_item_lux) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new LuxSensor()).commit();
            }

            return false;
        }

    });

    /**
     * Setup Drawer Toggle of the Toolbar
     */

    android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
            R.string.app_name);

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerToggle.syncState();



}

此菜单之一(片段)

public class LuxSensor extends Fragment {
TextView textLIGHT_available, textLIGHT_reading;
FragmentManager mFragmentManager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View x =  inflater.inflate(R.layout.lux_sensor,null);
    textLIGHT_reading
            = (TextView)x.findViewById(R.id.LIGHT_reading);

    SensorManager mySensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);

    Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    if(LightSensor != null){
        mySensorManager.registerListener(
                LightSensorListener,
                LightSensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    }else{
        textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
    }
    FragmentManager fm = getFragmentManager();

    return x;
}



private final SensorEventListener LightSensorListener
        = new SensorEventListener(){

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType() == Sensor.TYPE_LIGHT){
            textLIGHT_reading.setText(event.values[0]+" LUX");
        }
    }

};

}
我试过在互联网解决方案,但它仍然关闭

doinxwow

doinxwow1#

fragment中,您应该使用类似以下的内容:

@Override
    //Pressed return button - returns to the results menu
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                 //your code

                   return true;
                }
                return false;
            }
        });
    }
4bbkushb

4bbkushb2#

片段的onCreateView添加此
java

requireActivity().getOnBackPressedDispatcher().addCallback(activity, new OnBackPressedCallback(true) {
    @Override
    public void handleOnBackPressed() {
        // in here you can do logic when backPress is clicked
    }
});

Kotlin

requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // in here you can do logic when backPress is clicked
    }
})
cmssoen2

cmssoen23#

在主活动中,您需要覆盖以下函数

@Override
public void onBackPressed()
{
     // code here to check what fragment you are on and handle that accordingly
     super.onBackPressed();  // this exits the app.
}

文档可从以下位置获得:https://developer.android.com/reference/android/app/Activity.html#onBackPressed()

qhhrdooz

qhhrdooz4#

在您的主活动中

@Override
public void onBackPressed()
{
    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.containerView,new Recommendation()).commit();
}
imzjd6km

imzjd6km5#

使用此(Kotlin中)

activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
    // in here you can do logic when backPress is clicked
}

})
我认为这是最优雅的方式

szqfcxe2

szqfcxe26#

你可以在android中使用setOnKeyListener()来实现按键监听器,然后,如果你想处理回按,覆盖onKey方法:

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
         // do your thing
    }

}
31moq8wy

31moq8wy7#

现在,onBackPressed方法已被弃用,我们需要使用以下方法(简单得多!):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
          if(shouldInterceptBackPress()){
            // in here you can do logic when backPress is clicked
          }else{
            isEnabled = false
            activity?.onBackPressed()
          }
        }
    })
}

您可以在here中找到完整的说明。通过此示例,它显示了在您不确定是否需要使用back press事件时如何操作

相关问题