【问题标题】:How to add button using layout both defined in the main.xml?如何使用 main.xml 中定义的布局添加按钮?
【发布时间】:2012-06-18 00:20:12
【问题描述】:

我在 main.xml 文件中创建了按钮并在活动文件中对其进行了初始化,但我不确定如何使用 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>

【问题讨论】:

    标签: java android xml button


    【解决方案1】:

    使用setContentView() 告诉Android 为您使用哪个布局文件Activity

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      相关资源
      最近更新 更多