0

How can I add a View in my Activity from a instantiated object?

I have this class:

   public class Object {
       public Object (Context context) {
         this.context = context
       }
       public void my_method() {
          //Add something in my view
       }
    }

and my mainactivity:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                Object obj = new Object(this);
//when i call this method \/ i wanted to add anything in my view 
                obj.my_method();
} 

How can i do this?

Mike Laren
  • 8,028
  • 17
  • 51
  • 70

2 Answers2

1

Use this methodology to get the activity main view: https://stackoverflow.com/a/4488149/785121

Then pass it to your method: obj.my_method(view)

Community
  • 1
  • 1
nirs
  • 333
  • 1
  • 5
-1

You should start by specifying the component where your object will put the view. For example, add a LinearLayout to your activity_main.xml and find a reference to it:

setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.my_layout);

Once you have that reference, pass it as a constructor argument to your Object, or as an argument to my_method(). For example:

Object obj = new Object(this, layout);

or

obj.my_method(layout);

Finally, make your method create the views and add it to the container:

public void my_method() {
    layout.addView(...);
}
Mike Laren
  • 8,028
  • 17
  • 51
  • 70