Search code examples
javaandroidonclicklistener

Can not trigger on Click


Can not trigger on Click listener

I tried

setClickable(true);

but still not working

minimum sdk is 15

the code doesn't have xml file, i need to fix it programmatically

the complete code:

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

so, why and how to fix it. at clicking the associated text will be printed


Solution

  • Try onClickListener inside your loop

     Cell cell = new Cell(this, txt, 50, 50);
     cell.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        System.out.println("value is " + value);
    
                    }
                });