如何从自定义视图访问片段中的onclicklistener

时间:2016-12-19 14:11:59

标签: java android android-fragments

我有一组以3x3网格排列的单选按钮。当我点击任何单选按钮时会出现一个toast,但是在自定义视图中调用onclick方法,我希望在片段中调用onclick方法。

我的自定义视图

public class ToggleButtonGroupTableLayout  extends TableLayout  implements OnClickListener {
OnItemClickCallback onItemClickCallback;
private static final String TAG = "ToggleButtonGroupTableLayout";
private RadioButton activeRadioButton;

/**
 * @param context
 */
public ToggleButtonGroupTableLayout(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}
public ToggleButtonGroupTableLayout(Context context,OnItemClickCallback onItemClickCallback) {
    super(context);
    this.onItemClickCallback = onItemClickCallback;
    // 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();

    activeRadioButton = rb;
}


public void radio_button_data(String s) {


}

/* (non-Javadoc)
 * @see android.widget.TableLayout#addView(android.view.View, int, android.view.ViewGroup.LayoutParams)
 */
@Override
public void addView(View child, int index,
                    android.view.ViewGroup.LayoutParams params) {
    super.addView(child, index, params);
    setChildrenOnClickListener((TableRow)child);
}


/* (non-Javadoc)
 * @see android.widget.TableLayout#addView(android.view.View, android.view.ViewGroup.LayoutParams)
 */
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
    super.addView(child, params);
    setChildrenOnClickListener((TableRow)child);
}


private void setChildrenOnClickListener(TableRow tr) {
    final int c = tr.getChildCount();
    for (int i=0; i < c; i++) {
        final View v = tr.getChildAt(i);
        if ( v instanceof RadioButton ) {
            v.setOnClickListener(this);
        }
    }
}

public int getCheckedRadioButtonId() {
    if ( activeRadioButton != null ) {
        return activeRadioButton.getId();
    }

    return -1;
}

我的片段

public class Post_Property_1 extends Fragment{

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ToggleButtonGroupTableLayout.OnItemClickCallback callback = null;
    // Inflate the layout for this fragment
    final View v = inflater.inflate(R.layout.post_property_1, container, false);}

请帮助我如何在片段活动中从自定义视图访问onclick。提前谢谢。

0 个答案:

没有答案