【问题标题】:Android. Material design button programmatically安卓。以编程方式的材料设计按钮
【发布时间】:2016-05-09 22:36:35
【问题描述】:

我想显示这样的材料设计按钮:

我正在使用MaterialDesignLibrary。在 XML 中,我可以这样显示:

<com.gc.materialdesign.views.ButtonRectangle
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#1E88E5"
                android:text="Button" />

如何以编程方式显示此按钮?

【问题讨论】:

  • 告诉我你为什么要贬低我?

标签: android material-design android-button


【解决方案1】:

更新:

首先在你的项目中扩展类:

public class MyButtonRectangle extends ButtonRectangle {

    public MyButtonRectangle(Context context) {
        super(context, null); //Pass null for AttributeSet Params
    }
}

与在 Android 中创建新的 MyButtonRectangle 相比:

MyButtonRectangle btn = new MyButtonRectangle(this);
btn.setId(R.id.someId); // you need to add dummy id in ids.xml in values folder.
btn.setText("Button");
btn.setBackgroundColor(getResources().getColor(R.color.colorName));

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Replace LinearLayout with your base layout like RelativeLayout,  FrameLayout,  etc.

btn.setLayoutParams(lp);

【讨论】:

  • 感谢您的回答!我也是这样的。但它有这个构造函数:ButtonRectangle(Context context, AttributeSet attrs)。你能帮忙吗:我不知道我应该为 AttributeSet attrs 发送什么?
  • 在您的 android 应用程序中扩展该类并添加一个新的构造函数以只读上下文。几分钟后检查我编辑的答案
  • 我已尝试按照您的建议使用自定义类。但它调用了 parent(ButtonRectangle) 的构造函数。构造函数需要 AttributeSet attrs。
  • 正如我所说,替换 ButtonRectangle btn = new ButtonRectangle(this); to MyButtonRectangle btn = new MyButtonRectangle(this);
  • 很抱歉,似乎没有简单的方法可以做到这一点。您必须将整个库作为模块导入并手动修改 ButtonRectangle Java 文件以支持单参数构造函数。或者按照这个:stackoverflow.com/questions/29379150/…
猜你喜欢
  • 2019-04-10
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
相关资源
最近更新 更多