【问题标题】:How can control button Text Size in customized Button class?如何在自定义 Button 类中控制按钮文本大小?
【发布时间】:2016-06-23 08:11:26
【问题描述】:

我的活动中有一些按钮从自定义类中膨胀,这些按钮使按钮完全正方形并适合它们在父项中取决于屏幕大小并且它工作正常:

public class MyButton extends Button {
public MyButton(Context context) {
    super(context);
}

public MyButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size); // make it square

}
}

这里是我的充气机:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button newGuessButton = (Button) inflater.inflate(R.layout.my_button, currentTableRow, false); 
currentView.addView(newGuessButton);

和 layout.xml:

<my.package.name.MyButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="100"/>

我的问题是如何在我的按钮中设置文本大小以根据需要更改默认大小。我想我必须在将其添加为视图之前对其进行设置,但我不知道如何?

【问题讨论】:

    标签: android android-layout android-custom-view android-button


    【解决方案1】:

    如果你只想设置文本大小,你可以使用属性

    android:textSize
    

    或使用方法

    Button.setTextSize()
    

    如果您想在按钮内放置文本,可以查看answer

    【讨论】:

    • !! D ,当然我必须 Button.setTextSize() 但将其设置为什么大小?
    • 查看我上面发送的链接
    • 我接受了你的回答并投了赞成票,谢谢。它有效。
    【解决方案2】:

    谢谢大家,但我找到了一种非官方方法:正如我所说,我的自定义类(最后)为我制作了一些填充父屏幕的按钮,并且取决于我想连续创建多少个屏幕以及屏幕的宽度大小或高度大小(我们需要更小的一个),我们可以找到最接近该数字的大小将像这样创建:(我想创建连续 5 个方形按钮)

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    Resources resources = getApplicationContext().getResources();
    scale = resources.getDisplayMetrics().density;
    display.getSize(size);
    int width = size.x;
    int tempSize = width / 5;// (5: number of buttons)
    float ff = (float) ((tempSize * 0.4) / (scale));// (0.4: for example)
    ....
    newGuessButton.setTextSize(ff);
    currentView.addView(newGuessButton);
    

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2011-01-24
      • 1970-01-01
      • 2012-08-27
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多