【问题标题】:programmatically put an Image button inside custom buttons of table layout以编程方式将图像按钮放在表格布局的自定义按钮中
【发布时间】:2015-06-07 19:17:29
【问题描述】:

我正在使用 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));


    }

【问题讨论】:

    标签: android button imagebutton android-tablelayout


    【解决方案1】:

    试试这个-

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

    【讨论】:

    • 另一种方法是创建一个按钮并将该按钮的背景设置为您想要的图像。
    • 我想在自定义按钮中添加图片按钮,但这段代码不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2023-03-02
    • 2012-09-29
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多