以编程方式将图像按钮放在表格布局的自定义按钮内

时间:2014-01-04 13:05:44

标签: android button imagebutton android-tablelayout

我在Android中制作游戏,并希望在自定义按钮内添加可点击的图像按钮,这些按钮是表格布局的单元格。在我的情况下,我需要以编程方式进行,因为它将是设备无关的代码。 我真的很坚持这个话题,请尽快帮助我。

谢谢


这是我的代码:

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


    }

1 个答案:

答案 0 :(得分:0)

试试这个 -

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

或以其他方式在背景中创建button图片 -

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