如何在单击按钮时启动新活动

在Android应用程序中,如何在单击另一个活动中的按钮时如何启动新活动(GUI),以及如何在这两个活动之间传递数据?


#1楼

伊曼纽尔

我认为应该在开始活动之前放置额外的信息,否则,如果您正在NextActivity的onCreate方法中访问数据,则数据将不可用。

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

#2楼

您可以尝试以下代码:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);

#3楼

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

#4楼

    Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);    
    startActivity(in);

    This is an explicit intent to start secondscreen activity.

#5楼

当用户单击按钮时,直接在XML内是这样的:

<Button
         android:id="@+id/button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="TextButton"
         android:onClick="buttonClickFunction"/>

使用属性android:onClick我们声明必须在父活动中出现的方法名称。 因此,我必须像这样在我们的活动中创建此方法:

public void buttonClickFunction(View v)
{
            Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
            startActivity(intent);
}

#6楼

从发送活动中尝试以下代码

   //EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
    public static final String EXTRA_MESSAGE = "packageName.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       ....

        //Here we declare our send button
        Button sendButton = (Button) findViewById(R.id.send_button);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //declare our intent object which takes two parameters, the context and the new activity name

                // the name of the receiving activity is declared in the Intent Constructor
                Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);

                String sendMessage = "hello world"
                //put the text inside the intent and send it to another Activity
                intent.putExtra(EXTRA_MESSAGE, sendMessage);
                //start the activity
                startActivity(intent);

            }

从接收活动中尝试以下代码:

   protected void onCreate(Bundle savedInstanceState) {
 //use the getIntent()method to receive the data from another activity
 Intent intent = getIntent();

//extract the string, with the getStringExtra method
String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);

然后只需将以下代码添加到AndroidManifest.xml文件中

  android:name="packagename.NameOfTheReceivingActivity"
  android:label="Title of the Activity"
  android:parentActivityName="packagename.NameOfSendingActivity"

#7楼

Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);

#8楼

当前的反应很好,但是对于初学者来说,需要一个更全面的答案。 有3种不同的方法可以在Android中启动新活动,它们都使用Intent类。 意图 Android开发人员

  1. 使用按钮的onClick属性。 (初学者)
  2. 通过匿名类分配OnClickListener() 。 (中间)
  3. 活动范围接口方法使用switch语句。 (专业版)

如果您想继续,以下是我的示例的链接

1.使用按钮的onClick属性。 (初学者)

按钮具有.xml文件中的onClick属性:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnActivity"
    android:text="to an activity" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnotherActivity"
    android:text="to another activity" />

在Java类中:

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

public void goToAnActivity(View view) {
    Intent intent = new Intent(this, AnActivity.class);
    startActivity(intent);
}

public void goToAnotherActivity(View view) {
    Intent intent = new Intent(this, AnotherActivity.class);
    startActivity(intent);
}

优点 :易于即时制作,模块化,并且可以轻松地将多个onClick设置为相同的意图。

缺点 :审查时可读性差。

2.通过匿名类分配OnClickListener() 。 (中间)

这是当您为每个button设置单独的setOnClickListener()并以其自己的意图覆盖每个onClick()时。

在Java类中:

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

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnActivity.class);
                view.getContext().startActivity(intent);}
            });

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnotherActivity.class);
                view.getContext().startActivity(intent);}
            });

优点 :易于即时制作。

劣势 :将有很多匿名类,这将使审阅时的可读性变得困难。

3.使用switch语句的活动范围接口方法。 (专业版)

这是在onClick()方法中对按钮使用switch语句来管理所有Activity的按钮时。

在Java类中:

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

    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button1:
            Intent intent1 = new Intent(this, AnActivity.class);
            startActivity(intent1);
            break;
        case R.id.button2:
            Intent intent2 = new Intent(this, AnotherActivity.class);
            startActivity(intent2);
            break;
        default:
            break;
    }

优点 :按钮管理简单,因为所有按钮意图都在一个onClick()方法中注册


对于问题的第二部分,传递数据,请参阅如何在Android应用程序的“活动”之间传递数据?


#9楼

启动新活动的方法是广播意图,您可以使用一种特定的意图将数据从一个活动传递到另一个活动。 我的建议是您检查与意图有关的Android开发人员文档; 这是关于该主题的大量信息,并且也有示例。


#10楼

简单。

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);

通过以下方式在另一侧检索额外内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("key"); //if it's a string you stored.
}

不要忘记在AndroidManifest.xml中添加新活动:

<activity android:label="@string/app_name" android:name="NextActivity"/>

#11楼

为ViewPerson活动创建一个意图,并传递PersonID(例如,用于数据库查找)。

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);

然后,在ViewPerson Activity中,您可以获取额外的数据包,确保它不为null(以防有时不传递数据),然后获取数据。

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

现在,如果您需要在两个活动之间共享数据,则还可以拥有一个全局单例。

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

然后通过以下任何方式在任何活动中调用它:

YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic

#12楼

试试这个简单的方法。

startActivity(new Intent(MainActivity.this, SecondActivity.class));

#13楼

从另一个活动开始一个活动是android应用程序中非常常见的情况。
要启动活动,您需要一个Intent对象。

如何创建意图对象?

一个意图对象在其构造函数中带有两个参数

  1. 语境
  2. 要启动的活动的名称 。 (或完整的包裹名称)

例:

在此处输入图片说明

因此,例如,如果您有两个活动,例如说HomeActivityDetailActivity并且想从HomeActivity (HomeActivity-> DetailActivity)启动DetailActivity

这是显示如何从以下位置启动DetailActivity的代码段

家庭活动。

Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);

您完成了。

回到按钮点击部分。

Button button = (Button) findViewById(R.id.someid);

button.setOnClickListener(new View.OnClickListener() {

     @Override
     public void onClick(View view) {
         Intent i = new Intent(HomeActivity.this,DetailActivity.class);
         startActivity(i);  
      }

});

#14楼

实现View.OnClickListener接口,并重写onClick方法。

ImageView btnSearch;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search1);
        ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(this);
    }

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSearch: {
                Intent intent = new Intent(Search.this,SearchFeedActivity.class);
                startActivity(intent);
                break;
            }

#15楼

从该活动开始另一个活动,您也可以通过Bundle Object传递参数。

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);

检索另一个活动(YourActivity)中的数据

String s = getIntent().getStringExtra("USER_NAME");

#16楼

尽管已经提供了正确的答案,但是我在这里是用Kotlin语言搜索答案的。 这个问题与语言无关,因此我添加了代码以Kotlin语言完成此任务。

这是您在Kotlin中为Andorid进行的操作

testActivityBtn1.setOnClickListener{
      val intent = Intent(applicationContext,MainActivity::class.java)
      startActivity(intent)

 }

#17楼

首先在xml中获取Button。

  <Button
        android:id="@+id/pre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher"
        android:text="Your Text"
        />

制作按钮的列表器。

 pre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });

#18楼

单击按钮时:

loginBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent= new Intent(getApplicationContext(), NextActivity.class);
        intent.putExtra("data", value); //pass data
        startActivity(intent);
    }
});

要从NextActivity.class接收额外的数据:

Bundle extra = getIntent().getExtras();
if (extra != null){
    String str = (String) extra.get("data"); // get a object
}

#19楼

在您的第一个活动中编写代码。

button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
                       //You can use String ,arraylist ,integer ,float and all data type.
                       intent.putExtra("Key","value");
                       startActivity(intent);
                        finish();
            }
         });

在secondActivity.class中

String name = getIntent().getStringExtra("Key");

#20楼

将按钮小部件放置在xml中,如下所示

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
/>

之后初始化并处理活动中的点击监听器,如下所示。

在Activity On Create方法中:

Button button =(Button) findViewById(R.id.button); 
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       Intent intent = new 
            Intent(CurrentActivity.this,DesiredActivity.class);
            startActivity(intent);
    }
});

#21楼

科特林

第一次活动

startActivity(Intent(this, SecondActivity::class.java)
  .putExtra("key", "value"))

第二次活动

val value = getIntent().getStringExtra("key")

建议

始终将密钥放置在常量文件中,以实现更好的管理方式。

companion object {
    val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
  .putExtra(PUT_EXTRA_USER, "value"))

#22楼

单击按钮打开活动的最简单方法是:

  1. 在res文件夹下创建两个活动,在第一个活动中添加一个按钮,并为onclick函数命名。
  2. 每个活动应有两个Java文件。
  3. 下面是代码:

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void goToAnotherActivity(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
}

SecondActivity.java

package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity1);
    }
}

AndroidManifest.xml(只需将此代码块添加到现有代码中)

 </activity>
        <activity android:name=".SecondActivity">
  </activity>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个例子,演示如何在Tkinter中使用线程,在点击启动按钮启动线程,在点击停止按钮后停止线程: ``` import tkinter as tk import threading import time class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() def create_widgets(self): self.counter_label = tk.Label(self, text="0") self.counter_label.pack() self.start_button = tk.Button(self, text="Start", command=self.start_counter) self.start_button.pack() self.stop_button = tk.Button(self, text="Stop", command=self.stop_counter, state=tk.DISABLED) self.stop_button.pack() def start_counter(self): # 创建线程 self.counter_thread = threading.Thread(target=self.update_counter) # 启动线程 self.counter_thread.start() # 更按钮状态 self.start_button.config(state=tk.DISABLED) self.stop_button.config(state=tk.NORMAL) def stop_counter(self): # 停止线程 self.counter_running = False # 更按钮状态 self.start_button.config(state=tk.NORMAL) self.stop_button.config(state=tk.DISABLED) def update_counter(self): self.counter_running = True counter = 0 while self.counter_running: counter += 1 time.sleep(0.1) # 模拟耗操作 # 在GUI线程中更计数器的值 self.master.after(0, self.counter_label.config, {"text": str(counter)}) if __name__ == '__main__': root = tk.Tk() app = App(master=root) app.mainloop() ``` 在这个例子中,点击“Start”按钮后,程序会创建一个线程,该线程会不断地更计数器的值,并且每次更后会通过`self.master.after()`方法在GUI线程中更计数器的标签。同,“Start”按钮的状态会被禁用,“Stop”按钮的状态会被启用。当点击“Stop”按钮,程序会将`self.counter_running`标记为False,从而停止线程的执行,同按钮状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值