【问题标题】:TextView and Button same dimensions but showing differentlyTextView 和 Button 尺寸相同但显示不同
【发布时间】:2015-02-16 05:55:53
【问题描述】:

我正在动态创建 TextView 和 Button,但尽管我给它们提供相同的大小,但它们的显示方式却大不相同。

RelativeLayout journals = (RelativeLayout) findViewById(R.id.main);

layoutUserDoes = new RelativeLayout(this);

layoutUserDoes.setLayoutParams(new LayoutParams(journals.getWidth() , 100));
layoutUserDoes.setY(0);
layoutUserDoes.setBackgroundColor(Color.WHITE);
journals.addView(layoutUserDoes);

TextView t1=new TextView(this);
t1.setTextSize(20);
t1.setText("t1");
t1.setBackgroundColor(Color.GRAY);
t1.setTextColor(Color.BLACK);
t1.setWidth(50);
t1.setHeight(40);
t1.setX(20);

layoutUserDoes.addView(t1);

Button t2=new Button(this);
t2.setTextSize(20);
t2.setText("t2");
t2.setBackgroundColor(Color.GRAY);
t2.setTextColor(Color.BLACK);
t2.setWidth(50);
t2.setHeight(40);
t2.setX(71);

layoutUserDoes.addView(t2);

【问题讨论】:

  • 这是由于 TextView 和 Button 样式之间的差异在/res/values/styles.xml中检查您的样式
  • 我面临以下问题,也许我走错了路:我有可变数量的按钮和 TextViews(存储在一个数组中)放在屏幕的整个宽度上。结果应该很好地放在中间,每个都直接在前一个之后。这就是为什么我想去像素。我无法在 XML 布局中做到这一点。你有什么建议?

标签: android button layout textview


【解决方案1】:

你错过了一个概念。

当你使用

t2.setX(71);

您正在工作with pixels。但是每个设备都有不同的点密度。所以,在你的情况下, px 和 dp 不匹配。

要解决这个问题,您有两个选择

1.- 您可以在 xml 文件中静态定义按钮。

2.- 你可以写:

t2.setX(90);

我建议你第一个解决方案,如果你有时间你应该阅读this link。

希望对你有帮助。

【讨论】:

  • @michaelsmith 有用吗?没有?你找到解决办法了吗?
【解决方案2】:

你可以试试这个。

在 TextView 中设置与按钮相同的样式

style="@android:style/Widget.Button"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多