java - 如何使用 main.xml 中定义的布局添加按钮?

标签 java android xml button

我在 main.xml 文件中创建了按钮并在 Activity 文件中对其进行了初始化,但我不确定如何使用 xml 中定义的布局让按钮出现在屏幕上。谁能帮我解决这个问题?

public class MyTasteActivity extends Activity implements View.OnClickListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText("Hello, Android");

        Button collectionBtn = (Button) findViewById(R.id.collectionBtn);

    }

    public void collectionBtn(View v) {
        Toast.makeText(getApplicationContext(), "Collection was pressed", Toast.LENGTH_LONG).show();
    }

    public void onClick(View v) {}
}

XML 文件:

    <LinearLayout
        android:layout_width="310px"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/collectionBtn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="collectionBtn"
            android:text="Collection" />
        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 3" />

        <EditText
            android:id="@+id/txt"
            android:layout_width="fill_parent"
            android:layout_height="300px" />

        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 4" />

        <Button
            android:id="@+id/button5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 5" />
    </LinearLayout>

</ScrollView>

最佳答案

使用 setContentView() 告诉 Android 为您的 Activity 使用什么布局文件。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xml_file_name_here);
}

关于java - 如何使用 main.xml 中定义的布局添加按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11042040/

相关文章:

java - android:如果开/关/自动如何检查闪光灯?

xml - 如何验证 HTTP 重定向绑定(bind)的 SAML 签名

c# - 根据属性值复制部分 XML 文件

java - 无法在已刷新的页面上绘制元素

java - 如何在 Lotus Domino Designer 控制台中打印异常堆栈跟踪

java - 为什么 TRANSACTION_READ_COMMITTED 是 Java 中的默认值?

java - 双组-Cookie : PHPSESSID in http response

android - 如何使用数组列表中的数据填充自定义布局 ListView

java - Android 应用程序不幸的是应用程序已停止

java - XML 的最后一个子级抛出 NullPointerException