Search code examples
androidandroid-layoutlayoutoncreate

Android get custom view outside onCreate


I'm a beginner in Android Java developing so I'm not sure if I described the question at the best.

Anyway: I have created a Tileview in the onCreate function (see: https://github.com/moagrius/TileView) and added this Tileview to a custom relativelayout as follow:

TileView tileView = new TileView( this );
...
((RelativeLayout) findViewById(R.id.rootView)).addView(tileView);

This all works great. I do also have a drawer menu where the locations will be placed. The idea is that in the menu you can click on the locations, the Tileview will slide and zoom to that spot with:

tileView.slideToAndCenterWithScale(1000, 1000, (float) 0.4);

This works but I can only use the tileView inside my onCreate function. Can I make this view public or call it outside this function somehow?

What I've tried for my drawer menu is to get the view by:

TileView tileView = (TileView) findViewById(R.id.rootView);

This does not work because of 'Unexpected cast to TileView, probably because it's a RelativeLayout. How should I get the TileView created in the onCreate?

The whole drawer menu function:

@Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        TileView tileView = (TileView) findViewById(R.id.rootView);
        if (id == R.id.nav_entrance) {
            tileView.slideToAndCenterWithScale(1000, 1000, (float) 0.4);
        } else if (id == R.id.nav_tower) {
            tileView.slideToAndCenterWithScale(1500, 1500, (float) 0.4);
        }

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

Thanks in advance!


Solution

  • Make tileView a field/member of the same class you have your onCreate method, here is an example.

    TileView tileView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        tileView = new TileView( this );
        ...
        ((RelativeLayout) findViewById(R.id.rootView)).addView(tileView);
        ...
    }
    
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_entrance) {
            tileView.slideToAndCenterWithScale(1000, 1000, (float) 0.4);
        } else if (id == R.id.nav_tower) {
            tileView.slideToAndCenterWithScale(1500, 1500, (float) 0.4);
        }
    
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }