如何在mainactivity而不是自定义视图中为gridview单选按钮设置onclick侦听器

时间:2016-12-19 10:22:38

标签: java android

我想为onclicklistener中的单选按钮设置MainActivity,现在我已经在自定义视图中点击了。

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;
    }

}

如何将onclick侦听器移动到MainActivity?

1 个答案:

答案 0 :(得分:0)

您可以将自定义视图与主活动放在同一个类中,然后您可以轻松访问它,或者您可以在适配器中传递单击侦听器并在主活动中超越OnClick并执行所需的操作:

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);
    }
}

添加此类并在adpater中传递其对象