简体   繁体   中英

Sharing text in editText using other apps

I have been trying a simple app in Java and I´d like to know how to use a text written into editText in my code. Specifically, I want to make a "Share" button, which would send a text written in editText using different messaging app. Here is my code:

    public void share (View view){
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.setType("text/plain");
    startActivity(sendIntent);

Now, when I press the button, it just sends the "This is my text to send." sentence. How do I change this so the button uses text written in editText?

Thanks for answers

share is called upon clicking on a share button and edit id is related to your EditText from where you want to get your text.

public void share(View view){

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    EditText msg = (EditText)findViewById(R.id.edit);
    String finalMsg = String.valueOf(msg.getText().toString().trim());
    intent.putExtra(Intent.EXTRA_TEXT, finalMsg);
    Intent modIntent = Intent.createChooser(intent, "Send With..");
    startActivity(modIntent);
}

Try this:

EditText et = (EditText)findViewById(R.id.editTextId);
public void share (View view){
    String currentText = et.getText().toString().trim();
    if(currentText.isEmpty())
    {
        Toast.makeText(getContext(),"Cannot be blank",Toast.LENGTH_LONG).show();
        return;
    }
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, currentText);
    sendIntent.setType("text/plain");
    startActivity(sendIntent);
}

Instead of "This is my text to send." Collect whatever is written in the editText text field and then send it. Give the share button and the editText an id and use those ids to collect the data.

    btn = (Button) findViewById(R.id.button);
    enteredText = (EditText) findViewById(R.id.etNum1);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String a = String.valueOf(enteredText.getText().toString());

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM