grunk
grunk

Reputation: 14948

How to startActivityForResult with android-actionBar?

i'm using android-actionbar (https://github.com/johannilsson/android-actionbar) to create actionbar in my application. For adding a button, (an action) i use this code :

Intent myIntent = new Intent(this,SelectionCamera.class);
myIntent.putExtra("ledp",(Parcelable)Dp);
myIntent.putExtra("cam",this.numCam );
IntentAction actionCam = new IntentAction(this, 
                myIntent, 
                R.drawable.ic_camera
            );
actionBar.addAction(actionCam);

This working just fine , but i need to start the activity and get result from it(startActivityForResult()). It seems easy with the mimic-native-api branche but i would rather not change my actionBar version. Any solution ?

Upvotes: 2

Views: 1244

Answers (1)

Lorne Laliberte
Lorne Laliberte

Reputation: 6311

Edit: I currently recommend using ActionBarSherlock instead of android-actionbar. It allows use of the native Android action bar on newer devices and provides full API compatibility on older ones.


Original answer:

I would recommend the mimic-native-api branch, it is more up to date and has some very useful features such as being able to define actions from XML. (I'm using it in a large project and it's working splendidly.)

However, you should be able to do this in the master branch by creating your own implementation of AbstractAction -- e.g. add another class similar to IntentAction called "ResultAction" and have it use mContext.startActivityForResult(mIntent) instead of mContext.startActivity(mIntent). You'll also need to store the requestCode that you want to watch for in your onActivityResult.

Some completely untested example code:

public static class ResultAction extends ActionBar.AbstractAction {
    private Context mContext;
    private Intent mIntent;
    private int mRequestCode;

    // note: you could use this to start activities normally (with no result)
    //       by using a negative value for requestCode.
    public ResultAction(Context context, Intent intent, int drawable, int requestCode) {
        super(drawable);
        mContext = context;
        mIntent = intent;
        mRequestCode = requestCode;
    }

    @Override
    public void performAction(View view) {
        try {
           mContext.startActivityForResult(mIntent, mRequestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(mContext,
                    mContext.getText(R.string.actionbar_activity_not_found),
                    Toast.LENGTH_SHORT).show();
        }
    }
}

You'll need to override onActivityResult in your activity to get the result code, as documented here.

Upvotes: 3

Related Questions