BinnoBa BinnoBa - 6 months ago 20
Android Question

android button in class

i'm a very newbie in android programming so sorry for this question :D

All i want to do is to have a class that creates dynamically a button and fills it with the text 'tarr' automatically. So i generated a new class and wrote the following in it:

import android.widget.Button;

public class FloatButton {
Button button = new Button(this);

button.setText("tarr");
}


in my main activity it should make an object of this class. So i wrote this in the activity (snippet):

...

public void onCreate() {
super.onCreate();

FloatButton myButton = new FloatButton();
}


Sadly this gives me some mistakes marked. The mistake i don't realy understand is why the 'this' is marked. Can you tell me the problem?

Answer

When sending this to the Button constructor method, you are not sending a valid Context, but your FloatButton object.

Android Context

What you can do is :

   public class FloatButton {
        private Context _context;

        public FloatButton(Context context) {
          this._context = context;
        }
        public createButton() {
          Button mButton = new Button(_context);
          mButton.setText("tarr");
        }
    }

PS : Why are you trying to create a button in a separate class, and not directly in your activity ?