Nino van Hooff
Nino van Hooff

Reputation: 3893

Call public method on main activity

My main class has a public method called commitChanges(). My layout contains extended EditTexts which can detect when the back button is pressed, as suggested here: Get back key event on EditText

Now, when a back button press is detected, I need to execute commitChanges, which stores the content to an array. commitChanges needs access the activity's listview however.

The question is: how to access the commitChange function of the main activity? I will need the instance of the main activity. Heres the code of the extended EditText:

    public class BackText extends EditText{

private static final String TAG = "baby";
public BackText(Context context) {
    super(context);

}

public BackText(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public BackText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && 
        event.getAction() == KeyEvent.ACTION_UP) {
            Log.d(TAG,"keypad exit");
            commitChange(this);
            return false;
    }
    return super.dispatchKeyEvent(event);
}

}

Note i'm a beginner and this pretty advanced for me. Note 2: this has nothing to do with services/multiple activities. The BackTexts are placed in the main activity.

Upvotes: 0

Views: 986

Answers (2)

Nino van Hooff
Nino van Hooff

Reputation: 3893

I solved this by adding the following sub class to my main activity class:

class backReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"BACK received");
        BackText bt = (BackText)tlv.findViewWithTag(EDIT_TAG);
        bt.setTag(null);//only needed for id between caller/receiver
        commitChange(bt);
    }

}

And adding the following to oncreate of main activity:

IntentFilter filter = new IntentFilter("com.commonsware.cwac.tlv.demo.commit");

BroadcastReceiver receiver = new backReceiver();
registerReceiver(receiver,filter);

And adding this to BackText a EditText extension:

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && 
        event.getAction() == KeyEvent.ACTION_UP) {
            Log.d(TAG,"keypad exit");
            Intent intent = new Intent("com.ninovanhooff.babynames.commit");
            this.setTag("EDIT");
            getContext().sendBroadcast(intent);
            return false;
    }
    return super.dispatchKeyEvent(event);
}

Upvotes: 0

TotoroTotoro
TotoroTotoro

Reputation: 17612

I would add a broadcast receiver to your activity, and fire a broadcast intent from your widget code. I would avoid the kind of tight coupling between the widget and the activity that you propose.

Upvotes: 1

Related Questions