0

到目前为止,我的应用程序非常简单且小巧。它到处都有一些按钮,但我可以看到它很快就会因大量按钮而失控。所以我的问题真的是,我的 activity_main.xml 看起来非常丑陋。它有一堆标签,所以我想知道,当你有很多标签时,生成按钮的“正确”方法是什么?

4

2 回答 2

2

使用 XML 定义视图。我总是建议你使用 xml,即使有 20 个按钮。

或者,您还可以在代码中以编程方式将按钮设置为您的布局。只需设置布局参数即可。

否则(如果您有许多按钮的列表并且需要滚动)ListView 或 GridView 将是一个不错的选择。

于 2013-07-04T17:19:43.930 回答
1

To make things cleaner in your XML, you can use include to reference other XML which defines a generic button with all its common properties.

So the button would be defined under genericbutton.xml placed in the layout folder:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick" />

</merge>

And then your main activity_main.xml will have something like this for three buttons:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include
        android:id="@+id/button1"
        layout="@layout/genericbutton" />

    <include
        android:id="@+id/button2"
        layout="@layout/genericbutton" />

    <include
        android:id="@+id/button3"
        layout="@layout/genericbutton" />
</LinearLayout>

But in this case, you either set the same text for the buttons inside the genericbutton.xml or one by one in Java code. You cannot set it in the include tags.

于 2013-07-04T17:42:00.587 回答