单击时无法触发

时间:2018-03-25 17:21:19

标签: java android onclicklistener

无法在Click侦听器上触发

我试过

  

setClickable(真);

但仍无法正常工作

  

最小sdk为15

代码没有xml文件,我需要以编程方式修复它

完整的代码:

public class MainActivity extends AppCompatActivity {

private static char CHAR = 'a';

private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL); 

    int rowNo = ROWS;
    int colNo = (screenWidth().widthPixels * ROWS /screenWidth().heightPixels) ;
    for (int i = 0; i < 5; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        for (int j = 0; j < 5; j++) {
            String txt = String.valueOf(CHAR);
            Cell cell = new Cell(this, txt, 50, 50);
            cell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    System.out.println("value is " + txt);

                }
            });
            row.addView(cell);
            CHAR += 1;
        }
        layout.addView(row);
    }
    setContentView(layout);
}

private class Cell extends LinearLayout{

    public Cell(Context context, final String value, int width, int height) {
        super(context);
        LinearLayout.LayoutParams cellParams = new LinearLayout.LayoutParams(width, height);
        setLayoutParams(cellParams);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setBackground(getGradientDrawable());
        }else{
            setBackgroundDrawable(getGradientDrawable());
        }

    }
    private GradientDrawable getGradientDrawable() {
        GradientDrawable shape = new GradientDrawable();
        shape.setShape(GradientDrawable.RECTANGLE);
        shape.setColor(Color.TRANSPARENT);
        shape.setStroke(2, Color.BLACK);
        return shape;
    }
}
}

所以,为什么以及如何解决它。 点击相关文字将被打印

1 个答案:

答案 0 :(得分:1)

在循环中尝试onClickListener

public override void ViewDidLoad()
        {

            SFCalendar calendar = new SFCalendar();
            containerView.AddSubview(calendar);

            containerView.AtBottomOf(this.View);
            containerView.AtTopOf(this.View);
            containerView.WithSameWidth(this.View);

            calendar.AtBottomOf(containerView);
            calendar.AtTopOf(containerView);
            calendar.WithSameWidth(containerView);
        }