0

I am making a game in android and want to add an clickable image button inside custom buttons which are cells of table layout. In my case i need to do it programmatically as it will be device independent code. i am really stuck on to the topic kindly help me asap.

thank you


This is my code:

    TableLayout table;
    int level=3;
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width1 = size.x;
    int height1 = size.y;
    //int totalheight;
    int btsize = width1 / level;
    int btsize1 = height1 / level;

    table = (TableLayout) findViewById(R.id.tableLayout1);
    table.setBackgroundResource(R.drawable.stage1);
    ImageButton img4 = new ImageButton(this);
    img4.setImageResource(R.drawable.bjp);
    for(int i=0; i<3; i++)
    {
        TableRow rowi = new TableRow(this);
        for(int j=0; j<3; j++)
        {
            // create a new Button         
            Button tj = new Button(this);         
            tj.setBackgroundResource(R.drawable.shape);
            rowi.addView(tj); //Attach View to its parent (row)
            TableRow.LayoutParams params = (TableRow.LayoutParams)tj.getLayoutParams();
            params.setMargins(1,1,1,1);
            tj.setWidth(btsize);
            tj.setHeight(btsize);
            //tj.setMinimumWidth(0);
            //tj.setMinimumHeight(0);
            tj.setLayoutParams(params);
            tj.setClickable(false);
            rowi.addView(img4);

        }
        table.addView(rowi, 
                new TableLayout.LayoutParams
                (LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT));


    }
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Nitish Jha
  • 1
  • 1
  • 3

1 Answers1

0

Try this-

LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout2);
ImageButton b = new ImageButton(this);
b.setText("ImageButton");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
i1Btn = R.drawable.image_name;
i1.setImageResource(i1Btn);
b.setOnClickListener(this);
ll.addView(b);

Or other way create button with image in background-

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setOnClickListener(this);
btn.setText("New Todo");
btn.setBackgroundResource(R.drawable.image_name);
ll.addView(btn);
Kanwaljit Singh
  • 4,339
  • 2
  • 18
  • 21