如何在if语句中覆盖onBackPressed?

时间:2015-07-30 02:58:49

标签: android android-activity

我的目标是覆盖我的onBackPressed方法的代码..

我已覆盖onBackPressed

中的activity
 @Override
 public void onBackPressed() {
    this.finish();
 }

以下代码位于onCreate()内,我如何覆盖onBackPressed来执行类似转到另一个意图的操作,

if(mode.equals("edit")){
  //onBackPressed();
}

修改!! 抱歉不明白的问题, 我想知道的是,有没有办法在onCreate方法的if语句中覆盖方法?

3 个答案:

答案 0 :(得分:3)

这样做:

 @Override
 public void onBackPressed() {

     // Check your mode in onBackPressed
     if(mode.equals("edit")){

         // Launch the intent
         Intent editIntent = new Intent(MyActivity.this, EditActivity.class);
         startActivity(editIntent);

     // else call to the super class method, for default behavior 
     }else{
         super.onBackPressed();
     }
 }

没有什么可以阻止你从Activity类中的任何方法进行onBackPressed调用:

    public class MainActivity extends AppCompatActivity {

            private int editMode = 1;
            private String mode = "edit";

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

                 // This is totally legal to do
                 if(editMode == 1){
                       onBackPressed();
                 }
            }
    }

答案 1 :(得分:0)

我想你想根据主叫位置执行一些操作, 因为我认为你可以按照下面给出的方法:

<div ng-controller="artistCtrl as Ctrl"> <!-- this is what you should look for -->
    <select ng-model="Ctrl.artistOrder"> <!-- check how we are using it to get property set on instance -->
        <option value="name">Name</option>
        <option value="reknown">Reknown</option>
    </select>
</div>

app.controller('artistCtrl', ['$http', function ($http) {
    var store = this; // this is controller instance not scope
    store.artistList = [];
    $http.get('js/data.json').success(function (data) {
        store.artistList = data;
    });
    store.artistOrder = 'name';
}]);

我希望这就是你想要的

答案 2 :(得分:0)

由于方法 onBackPressed()公开方法,您可以这样做:

在onCreate(){

    if(mode.equals("edit")){
        onBackPressed();
    }
    else
        Log.d("dj","something else");

}

onBackPressed中的

,我这样做是为了测试:

@Override
public void onBackPressed() {

    Log.d("dj", "Yeah! on back pressed");
    //super.onBackPressed();
}