From one Activity To other Activity

本文介绍了一个简单的Android应用程序,该程序包含两个Activity:MainActivity用于输入消息并通过按钮触发发送操作;DisplayMessageActivity则负责显示从MainActivity接收到的消息内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.layout 文件  content_main.xml

   

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context="com.sh.appfirst.MainActivity">


    <EditText
        android:id="@+id/message"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message"
        />
    <Button
        android:text="@string/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendMessage"

        />

>
2.java 文件 

MainActivity.java

public class MainActivity extends AppCompatActivity {
//   public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    /*    是public函数
            无返回值
    参数唯一(为View类型,代表被点击的视图)
    */
    public  void sendMessage(View view)
    {
//        Toast.makeText(this, "clicked button", Toast.LENGTH_SHORT).show();
   /*     在这个Intent构造函数中有两个参数:

        第一个参数是Context(之所以用this是因为当前Activity是Context的子类)

        接受系统发送Intent的应用组件的Class(在这个案例中,指将要被启动的activity)。

        Android Studio会提示导入Intent类。
        */
      Intent intent =  new Intent(this,DisplayMessageActivity.class);
       EditText editText =  (EditText)findViewById(R.id.message);
//     把EditText的文本内容关联到一个本地 message 变量,并使用putExtra()方法把值传给intent.
       String message = editText.getText().toString();

       /*  putExtra:将数据以key:value的形式放入一个Parcelable对象中,直接由Intent对象携带,适合少量数据。
           setData:将数据以数据流的方式传输,Intent接收后再单独接收Data部分,适合数据量较大的数据传输,如文件或图片等。
        */
        intent.putExtra("EXTRA_MESSAGE",message); //Intent可以携带称作 extras 的键-值对数据类型。 putExtra()方法把键名作为第一个参数,把值作为第二个参数。
         startActivity(intent);

            }

 

}

   
3.另一个Activity 文件  
  DisplayMessageActivity.java
  
public class DisplayMessageActivity extends AppCompatActivity {

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

//        得到intent 并赋值给本地变量.
        Intent intent = getIntent();

//        调用 getStringExtra()提取从 MyActivity 传递过来的消息.
//        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        String message = intent.getStringExtra("EXTRA_MESSAGE");
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(message);

        RelativeLayout layout =   (RelativeLayout)findViewById(R.id.content);
        layout.addView(textView);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

 

 
}
### Activity Diagram in Software Engineering An activity diagram is a graphical representation of workflows within a system. This type of Unified Modeling Language (UML) diagram describes the flow from one activity to another, showing how activities are dependent on each other and how they contribute to achieving an overall goal[^1]. Activity diagrams can model sequential as well as concurrent processes, which makes them particularly useful for visualizing complex business rules or operational procedures. These diagrams include elements such as actions, decision points, forks/joins for concurrency control, swimlanes to categorize related activities by responsibility, and object flows that show data being passed between actions. #### Definition In software engineering, an activity diagram serves as both design documentation and analysis tool. It captures not only what needs to happen but also under what conditions certain operations should occur. By representing logic through nodes connected via directed edges, these diagrams provide clear insight into procedural aspects without delving too deeply into implementation specifics. #### Usage The primary uses of activity diagrams encompass several areas: - **Business Process Modeling**: Capturing high-level views of organizational workflows. - **Algorithm Implementation Planning**: Detailing step-by-step instructions before coding begins. - **Use Case Expansion**: Elaborating upon use cases with more detailed sequences of events. - **Concurrency Analysis**: Identifying parallel tasks within systems where multiple threads operate simultaneously. #### Examples Consider an online shopping cart checkout process modeled using an activity diagram: ```mermaid graph TD; A(Start Checkout) --> B{Customer Logged In?}; B -- Yes --> C[Proceed Directly]; B -- No --> D(Display Login/Register Options); D --> E(Customer Chooses Option); E --> F(Login Form Shown); E --> G(Register New Account); H(Fill Out Shipping Info) --> I(Payment Method Selection); J(Process Payment & Confirm Order Details) --> K(Order Confirmation Page Displayed); C --> H; F --> H; G --> H; ``` This example illustrates various paths customers might take during checkout depending on their login status while highlighting key steps involved like filling out shipping information and selecting payment methods. --related questions-- 1. How do activity diagrams differ from state machine diagrams? 2. What tools support creating professional-looking UML activity diagrams? 3. Can you explain how swimlanes enhance readability when used inside activity diagrams? 4. Are there any best practices recommended specifically for drawing effective activity diagrams? 5. Provide some real-world applications beyond e-commerce scenarios where activity diagrams prove beneficial.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值