朋友我是Android编程的新手,我想了解我们如何选择文本并将所选文本返回到String中。
答案 0 :(得分:0)
如果要从EditText中选择文本,可以使用:
String selectedText = editText.getText().substring(startSelection, endSelection);
其中:
int startSelection=editText.getSelectionStart();
int endSelection=editText.getSelectionEnd();
但是,如果您有TextView,则需要在选择文本时创建自己的ActionMode.Callback。要查看快速示例,请转到此post。
答案 1 :(得分:0)
这里是一个快速示例,您可以选择文本并使用Toast将其显示在屏幕上:
MainActivity
public class MainActivity extends AppCompatActivity {
private static final int TRANSLATE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView mTextView = (TextView) findViewById(R.id.txt);
mTextView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0,TRANSLATE,0,"Translate").setIcon(R.drawable.ic_translate); //choose any icon
// Remove the other options
menu.removeItem(android.R.id.selectAll);
menu.removeItem(android.R.id.cut);
menu.removeItem(android.R.id.copy);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case TRANSLATE:
int min = 0;
int max = mTextView.getText().length();
if (mTextView.isFocused()) {
final int selStart = mTextView.getSelectionStart();
final int selEnd = mTextView.getSelectionEnd();
min = Math.max(0, Math.min(selStart, selEnd));
max = Math.max(0, Math.max(selStart, selEnd));
}
final CharSequence selectedText = mTextView.getText().subSequence(min, max); //this is your desired string
Toast.makeText(getApplicationContext(),selectedText,Toast.LENGTH_SHORT).show();
//Here put your code for translation
mode.finish();
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:textIsSelectable="true"
android:id="@+id/txt"
android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />