【问题标题】:How to create a custom button and add it programmatically?如何创建自定义按钮并以编程方式添加它?
【发布时间】:2018-01-14 03:13:55
【问题描述】:

我需要创建一个自定义按钮并以编程方式添加它。
我已经找到了一些我尝试过的例子,但是当我将它添加到我的活动中时,我什么也看不到。

这是我的代码:

活动:

        Button btn = new Button(Einstellungen.this, null, R.attr.CustomButton);

在 attrs.xml 中:

<resources>
<attr name="CustomButton" format="reference"/>

在styles.xml中

    <style name="AppTheme2" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="CustomButton">@style/someStyle</item>
</style>

<style name="someStyle">
    <item name="android:layout_width">2px</item>
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">#000</item>
</style>

当我启动我的应用时,没有按钮。
我该如何解决这个问题?

【问题讨论】:

  • 接受有助于您解决问题的答案。

标签: android xml styles


【解决方案1】:

您需要在声明按钮后执行此操作:

 layout = (LinearLayout) findViewById(R.id.linear_layout_of_your_xml);
 btn.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(buyButton);

如果你的 xml 有不同的布局,你甚至可以初始化并分配它而不是 LinearLayout

【讨论】:

  • 我试过了,但我的 Activity 中仍然没有任何东西可以设置:(
  • 请将您的java文件连同xml一起发布,以便我们进一步了解
【解决方案2】:

您还应该定义按钮的布局参数(如果未在样式中定义)并将按钮放入活动的布局中。假设你有 LinearLayout 的 id 为 activity_layout,那么它可能是这样的:

LinearLayout layout = (LinearLayout) findViewById(R.id.activity_layout);
Button button = new Button(Einstellungen.this, null, R.attr.CustomButton);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(layoutParams);
layout.addView(button);

请注意,您应该使用match_parent 而不是您定义的样式中的fill_parent。来自docs

fill_parent 表示视图希望与其父级一样大,减去父级的填充(如果有)。从 API 级别 8 起,该值已被弃用,取而代之的是 match_parent

【讨论】:

  • 我试过了,但我的 Activity 中仍然没有什么可以设置的 :(
  • 尝试删除样式并仅使用Button button = new Button(this); 定义按钮。另外 - 您应该在活动的 OnCreate() 方法中运行此代码。
  • 好的 Button button = new Button(this);工作中。显然我在 style.xml 中有一个错误?
  • 是的,看起来是这样。尝试将布局宽度和高度设置为“wrap_content”或“match_parent”
  • 什么都没有改变:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 2016-03-06
  • 1970-01-01
相关资源
最近更新 更多