简体   繁体   English

android中按钮的自定义布局

[英]Custom layout of button in android

How to custom layout of a button? 如何自定义按钮的布局? I want to create a button with layout like this: 我想创建一个布局如下的按钮:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="aaa" />
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="bbb" />
</LinearLayout>

The best and proper way is to create a subclass of Button, and inflate your custom XML layout in the constructor. 最佳和正确的方法是创建Button的子类,并在构造函数中填充自定义XML布局。 This way the custom button is reusable. 这样,自定义按钮是可重用的。

More information can be found here . 可以在此处找到更多信息。

Give that LinearLayout an id. 给该LinearLayout一个ID。 Add an onClickListener to that. 为此添加一个onClickListener and you got a button with that layout. 然后您得到一个带有该布局的按钮。

You can create a custom "button" from a View element by adding in xml to your view android:onClick="myFunction" and in code declare your function void myFunction(View v){ .. } . 您可以通过将xml添加到视图android:onClick="myFunction"并在代码中声明您的函数void myFunction(View v){ .. }来从View元素创建自定义“按钮”。

Or declare click listeners on your View in code 或在代码中的视图上声明点击监听器

LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearButton); 
myLinearLayout.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
    myFunction(v);
}
});

void myFunction(View v){
//do something awesome here
}

This is the simplest way I think. 这是我认为的最简单的方法。 Or you can extend a Button class, add new XML styles for different button states (activated, highlighted, normal) http://developer.android.com/guide/topics/ui/controls/button.html 或者,您可以扩展Button类,为不同的按钮状态(激活,突出显示,正常)添加新的XML样式http://developer.android.com/guide/topics/ui/controls/button.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM