Search code examples
javaandroidmethodsviewgraphics2d

Call a method in the custom view from MainActivity.Java


I have created a custom view and it has been added to the layout.

    <com.example.moynul.myapplication.Draw
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/view"
    android:layout_above="@+id/button"
    android:layout_alignRight="@+id/button2"
    android:layout_alignEnd="@+id/button2"
    android:layout_marginBottom="52dp"
    />

From doing this I do not need to instantiate my Draw class in the MainActivity class.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

However this has limitations, since I cannot call a method in the Draw class.

public void buttonOnClick(View v)
{
    switch (v.getId())
    {
        case R.id.button:
            //call a method in the Draw class 
            break;
    }
}

I have tried turning my Draw (that extends view) in to a static class, and turning the method I want to access in a public static method. But the invalidate() does not like this.

My next attempt was to create a button on the custom view class via the GUI builder. It appears that you cannot make a button a child object of a custom view object.

My question: How can I access a method in my Draw class from the main class?


Solution

  • To reference your Draw class create global variable in your MainActivity

    Draw myDraw; 
    

    Next, set it in your onCreate

    myDraw = (Draw) findViewById(R.id.view);
    

    Finally, call it in your buttonOnClick

    case R.id.button:
        myDraw.method();
        break;
    

    OR If you only want to reference the variable in the buttonOnClick you can just do something like this

    case R.id.button:
        ((Draw) findViewById(R.id.view)).method();
        break;