0

I've got a class that implements Observable. This class is seperate to my activity class. Is it possible to edit views from the Observable class or do all edits have to happen via the activity class?

This class is instantiated as an object in my activity of course.

3 Answers 3

3

Use the following sample code. You can cast context to activity and then you can use findViewById in other classes. You just need to pass the context using this constructor.

public SampleClass{

    SampleClass(Context mContext) {
        Activity activity = (mContext instanceof Activity) ? (Activity) mContext : null;
        Button mButton = activity.findViewById(R.id.button1);
    }

}
1
  • Don't store a activity reference in a class member like this. Just use it as a local variable within the method. If you store it and the activity get's killed in the meantime before you release this reference (e.g. because of a simple screen rotation), you will get a memory leak. The garbage collector simple won't work on the activitys remains because there is still a reference left.
    – user658042
    Nov 29, 2011 at 20:18
1

You can edit the Views of an Activity from any class you want, just pass the correct references to them. And make sure that you make those edits on the main thread of course.

1

Adding to Hitesh's example, here's a wrapper that takes a context (to retrieve a reference to your activity) and a view (the element to test and control e.g. button)

/**
 * Sets the text size of a view according to the device's Display Metrics
 * @param context
 *  e.g. an activity containing the view
 * @param view
 *  e.g. a button in the activity
 */
public static void SetTextSizeForDevices(Context context, View view){

    Activity activity = (context instanceof Activity) ? (Activity) context : null;
    View mView = activity.findViewById(view.getId());
    Button mButton;
    TextView mTextView;
    if(mView instanceof Button){
        mButton = (Button) mView;
        mButton.setTextSize(TEXTSIZEMULTIPLIER * context.getResources().getDisplayMetrics().density);
    }
    if(mView instanceof TextView){
        mTextView = (TextView) mView;
        mTextView.setTextSize(TEXTSIZEMULTIPLIER * context.getResources().getDisplayMetrics().density);
    }
}

TEXTSIZEMULTIPLIER can be a global int e.g.

private static int TEXTSIZEMULTIPLIER = 16;

Call this static method on all the activity views you want to set text size for

Michael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.