简体   繁体   中英

How to set onclick listener for gridview radio buttons in mainactivity instead custom view

I want to set onclicklistener for radio buttons in MainActivity , Right now I have onclick in custom view.

public class ToggleButtonGroupTableLayout  extends TableLayout  implements OnClickListener {

    private static final String TAG = "ToggleButtonGroupTableLayout";
    private RadioButton activeRadioButton;

    /**
     * @param context
     */
    public ToggleButtonGroupTableLayout(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    /**
     * @param context
     * @param attrs
     */
    public ToggleButtonGroupTableLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onClick(View v) {
        final RadioButton rb = (RadioButton) v;
        if ( activeRadioButton != null ) {
            activeRadioButton.setChecked(false);
        }
        rb.setChecked(true);
        Toast.makeText(getContext(),rb.getText().toString(), Toast.LENGTH_SHORT).show();
        if(rb.getText().toString().equalsIgnoreCase("Apartment"))
        {


        }

        //radio_button_data(rb.getText().toString());
        activeRadioButton = rb;
    }

}

How can I move onclick listener to MainActivity?

You can make the custom view in the same class as the main activity and then you can access it easily or you can pass click listener in adapter and over ride OnClick in main activity and perform required actions:

public class OnItemClickListener implements View.OnClickListener {
    private int position;
    private OnItemClickCallback onItemClickCallback;

    public OnItemClickListener(int position, OnItemClickCallback onItemClickCallback) {
        this.position = position;
        this.onItemClickCallback = onItemClickCallback;
    }

    @Override
    public void onClick(View view) {
        onItemClickCallback.onItemClicked(view, position);
    }

    public interface OnItemClickCallback {
        void onItemClicked(View view, int position);
    }
}

Add this class and pass its object in adpater

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