【问题标题】:How do I prevent programatically generated buttons from center aligning in Android?如何防止以编程方式生成的按钮在 Android 中居中对齐?
【发布时间】:2014-01-06 20:56:57
【问题描述】:

我有一组根据从 SQLite 数据库中提取的项目数生成的按钮。按钮生成并正常工作,但它们居中对齐并均匀地间隔开。意思是如果有一个:按钮居中;如果有两个:它们从中心均匀分布;等等

我需要让它们保持左对齐并允许我使用边距将它们隔开。我知道如何使用参数设置边距,但不知道为什么它们默认居中在 TableLayout 行中。

除了对齐之外,代码再次工作并完美响应。我在其他活动中也遇到过类似的问题,我确定这是相关的。

我已经包含了一些可能显示我在做什么的代码:

imgTitleTable = (TableLayout) findViewById(R.id.imagesTableLayout);

int i = 0;
while (i < imgTitle.length) {
    if (i % 6 == 0) {
        tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        imgTitleTable.addView(tr);
        imgtr = new TableRow(this);
        imgtr.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        imgTitleTable.addView(imgtr);
    }
    // add images
    ImageButton imgButton = new ImageButton(this);
    imgButton.setImageResource(R.drawable.images_sample);
    imgButton.setLayoutParams(new LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
    imgButton.setBackground(null);
    imgButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent theIntent = new Intent(getApplicationContext(),
                    Viewer.class);
            startActivity(theIntent);
        }
    });
    // add img title
    TextView title = new TextView(this);
    title.setText(imgTitle[i]);
    title.setId(i);
    title.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, 1f));
    title.setGravity(Gravity.CENTER);
    title.setWidth(imgButton.getDrawable().getIntrinsicWidth());
    title.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent theIntent = new Intent(getApplicationContext(),
                    Viewer.class);
            startActivity(theIntent);
        }
    });
    tr.addView(imgButton);
    imgtr.addView(title);
    i++;
}

【问题讨论】:

    标签: android button alignment


    【解决方案1】:

    试试

    TableRow.LayoutParams params = new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT); 
    params.gravity=Gravity.LEFT;
    imgButton.setLayoutParams(params);
    

    【讨论】:

    • .setGravity() 为布局保留。由于 imgButton 是 ImageButton 的一种类型,因此导致错误。
    • 抱歉,我已经编辑了我的答案。我对表格布局不太熟悉,但我认为应该可以
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多