2017-07-01 56 views
0

我一直在嘗試一個簡單的Java應用程序,我想知道如何在我的代碼中使用寫入editText的文本。具體來說,我想創建一個「共享」按鈕,它將使用不同的消息應用程序發送以editText編寫的文本。這裏是我的代碼:使用其他應用程序在editText中共享文本

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); 

現在,當我按下按鈕時,它只是發送「這是我的文本發送」。句子。我該如何改變這個按鈕,使用editText編寫的文本?

感謝答案

+3

呼叫'的getText()。的toString()'的'EditText'得到用戶鍵入的內容,而不是使用硬編碼的'該值「這是我的文字進行發送。」'值。 – CommonsWare

回答

0

share在點擊分享按鈕,被稱爲和edit ID是要收到你的短信與您的EditText。

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); 
} 
1

試試這個:

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); 
} 
+0

當我使用這段代碼時,它: 1)不能在這裏解析符號editText'String currentText = editText.getText()。toString()。trim();'每次我嘗試它時發生這種情況 2)can不解析符號Toast here Toast.makeText(getContext(),「不能爲空」,Toast.LENGTH_LONG).show(); return;' – Jakulele

+0

@Jakulele聲明'et(EditText引用)'作爲類級別和Toast - 它檢查空白字符串只是註釋掉。 –

0

而不是 「這是我的文字進行發送。」收集editText文本字段中寫的任何內容,然後發送它。 給分享按鈕和editText一個id並使用這些id來收集數據。

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()); 

     } 
    }); 
相關問題