Android开发之实现消息分享(四)

功能:

一、通过点击按钮,获取输入框文本信息

二、实现信息分享

1、设计UI界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容" />

    <Button
        android:id="@+id/btn_share"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="分享" />

</LinearLayout>

效果图

2、创建类

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class ShareSheetActivity extends AppCompatActivity {

    EditText etInput;
    Button btnShare;

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

        //初始化UI界面
        etInput=findViewById(R.id.et_input);
        btnShare=findViewById(R.id.btn_share);

        //监听按钮的点击事件,获取文本框的输入
        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取输入内容
                String content = etInput.getText().toString().trim();

                //创建意图
                Intent myIntent = new Intent();

                //设置Action
                myIntent.setAction(Intent.ACTION_SEND);

                //将数据传给Intent(意图)
                // myIntent.putExtra(键,值)
                myIntent.putExtra(Intent.EXTRA_TEXT,content);

                //设置内容的类型
                //text/plain  表示内容为纯文本
                myIntent.setType("text/plain");

                //创建shareIntent
                Intent shareIntent= Intent.createChooser(myIntent,"my share");

                //启动ShareIntent
                startActivity(shareIntent);
            }
        });

    }
}

启动项目

 

猜你喜欢

转载自blog.csdn.net/qq_53376718/article/details/129598757