web-dev-qa-db-ja.com

フラグメントアンドロイドで戻るボタンが押されたことを検出する方法は?

フラグメント付きのナビゲーションドロワー付きのプロジェクトがあり、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();




}

これはメニューの1つ(フラグメント)

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

};

}

私はインターネットで解決策を試しましたが、それでも閉じました

6
Josh Parinussa

MainActivityで

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

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

メインアクティビティでは、次の関数をオーバーライドする必要があります

@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()

3
M Hornbacher

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
    }

}
0
Yashasvi