简体   繁体   中英

How to access setOnClickListener of a button in custom view in android?

I am very new to Android Development and this is my first Android App.

Here is how my MainActivity layout looks like:

在此处输入图片说明

And this is the Component Tree of the MainActivity

在此处输入图片说明

The gridView is a custom view and I have a resetGrid function in it which looks something like this

public class GridView extends View {

    resetGird(){
        // stuff that resets grid;
    }
}

Here is the problem I am facing:

I can access the setOnClickListener of the reset button in the MainActivity file but not in the GridView file where the resetGrid function is located.

        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PathFind.this, "reset", Toast.LENGTH_SHORT).show();
            }
        });

I want to access this setOnClickListener of the reset button in the GridView file also and call the resetGrid function whenever the button is pressed.

Not only that, my plan is to use all the controls listed in the image (start button, diagonal checkbox, speed slider) to control the GridView. But I can't seem to find a way to do that. All the controls are available in the main_activity but I can't use them in the GridView.

You are in the right way. The "trick" is to save GridView's instance in a MainActivity variable and then use its reference to call/execute GridView's methods (like "resetGrid()").

ResetButton lives OUTSIDE GridView so it's a bad pratice to reference "resetButton" from INSIDE GridView extended class.

Pseudo code:

class GridView extends View {
    public void resetGrid() {
       ...do reset stuff here...
    }
}

class MainActivity extends Activity {
    private GridView mGridView;
    private Button mResetButton;
    public onCreateView() {
        ...
        mGridView = findViewById(R.id.gridview);
        mResetButton = findViewById(R.id.resetButton);
        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGridView.resetGrid();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM