gpt4 book ai didi

android - 如何在主 .java 文件中添加另一个 Activity

转载 作者:行者123 更新时间:2023-11-29 18:15:28 24 4
gpt4 key购买 nike

这是我的主 java 文件中的代码。我将如何制作另一个按钮来连接 Activity 。如果我表达得不够好,请告诉我。我只需要在主 java 文件中添加另一个按钮。我已经在 list 中有一个 Activity 和一个类,我只需要将另一个代码块放入主 java 文件中。按钮的 ID 是 p40,xml 布局的名称是 p40.xml,类名为 p40.java, Activity 名为 p40。这是我目前的代码:

package com.duncan.hello.world;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.duncan.hello.world.R;

public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Button aButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
aButton = (Button) this.findViewById(R.id.button1);

aButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(HelloWorldActivity.this, OtherActivity.class);
startActivity(i);
}});
}
}

最佳答案

你应该这样做

// This code is copied from your code as is 
// to have a reference point as well as this is also
// code for adding click listener to button which you
// need to handle click and then do what you want.
// In this case you are launching an Activity
// Block of code you already have to use STARTS
aButton = (Button) this.findViewById(R.id.button1);

aButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(HelloWorldActivity.this, OtherActivity.class);
startActivity(i);
}});
// Block of code you already have to use ENDS

// This code is added for newButton which looks similar to above block
Button newButton
newButton = (Button) this.findViewById(R.id.button2);

newButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(HelloWorldActivity.this, AnOtherActivity.class);
startActivity(i);
}});

您必须在 layout/main.xml 文件中添加另一个 button1

关于android - 如何在主 .java 文件中添加另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8391140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com