¿Por qué mi interfaz de usuario de Android actúa como falsa cuando intento seleccionar texto?

Estoy trabajando en una aplicación de Android (API 15 y siguientes). En mi interfaz de usuario tengo un elemento TextView que me gustaría que la gente pudiera seleccionar y copiar desde. Aquí es cómo se ve mi elemento:

<LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" /> <TextView android:id="@+id/chat_info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:padding="8dp" /> <TextView android:id="@+id/chat_message" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_margin="2dp" android:padding="8dp" android:textSize="18sp" android:gravity="right" android:textColor="@color/BLACK" android:textIsSelectable="true"/> </LinearLayout> 

Este TextView se encuentra dentro de un ListView que se rellena con un SimpleCursorAdapter. Este ListView tiene este aspecto:

 <ListView android:id="@+id/chat_text_display" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="2dp" android:layout_marginRight="2dp" android:layout_marginBottom="2dp" android:layout_marginLeft="2dp" android:padding="5dp" android:background="@color/WHITE" android:divider="@null" android:divider_height="0dp" android:stackFromBottom="true" android:transcriptMode="alwaysScroll"/> 

El ListView está dentro de un LinearLayout:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/custom_border"> <ListView android:id="@+id/chat_text_display" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="2dp" android:layout_marginRight="2dp" android:layout_marginBottom="2dp" android:layout_marginLeft="2dp" android:padding="5dp" android:background="@color/WHITE" android:divider="@null" android:dividerHeight="0dp" android:stackFromBottom="true" android:transcriptMode="alwaysScroll"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0" android:orientation="horizontal" android:layout_marginTop="2dp" android:layout_marginRight="1dp" android:layout_marginBottom="2dp" android:layout_marginLeft="2dp"> <Button android:id="@+id/text_send" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="0" android:layout_gravity="center_vertical" android:enabled="false" android:text="@string/chat_button"/> <EditText android:id="@+id/chat_text_compose" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:minLines="3" android:maxLines="3" android:paddingLeft="8dp" android:background="@color/WHITE" android:hint="@string/chat_hint"/> </LinearLayout> </LinearLayout> 

Cada vez que intento hacer clic en el texto en chat_info o chat_message, no pasa nada. Sin embargo, cada vez que intento hacer doble clic en el texto:

  1. Toda mi interfaz de usuario se desplaza hacia abajo
  2. Aparece una "barra de herramientas" en la parte superior de la pantalla
  3. La "barra de herramientas" desaparece inmediatamente y mi pantalla vuelve a desplazarse

En la "barra de herramientas" esto es lo que veo:

Parece que es el diálogo de copia, pero desaparece inmediatamente.

Puedo insertar un TextView "stand alone" dentro de LinearLayout con un android:textIsSelectable="true" y el diálogo de copia funciona como debería; Lo que significa que permanecerá visible hasta que haya seleccionado "copiar".

La última información que puedo ofrecer es que mi LinearLayout está dentro de una actividad con pestañas usando fragmentos con ViewPager. Simplemente no veo cómo esto puede ser el problema porque, como he dicho, puedo agregar otro elemento (por ejemplo, TextView) dentro de LinearLayout y el diálogo Copiar funciona perfectamente. Pensé que añadiría esta pieza para una mayor claridad.

Todo lo que quiero hacer es seleccionar el texto en chat_info o chat_message para que pueda copiar y pegar el texto en otro lugar.

¿Algunas ideas?

¡¡¡NUEVA INFORMACIÓN!!!

Cuando selecciono el texto en el texto "chat_text_compose", la barra de herramientas Copiar aparece normalmente. En este punto, puedo seleccionar con éxito el texto en mis áreas de TextView. Extraño.

UPDATE: El código que controla este diseño

 public class Chat extends Fragment { private View rootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.chat, container, false); return rootView; } @Override public void onViewCreated(View rootView, Bundle savedInstanceState) { super.onViewCreated(rootView, savedInstanceState); displayChats(); } @Override public void onResume() { super.onResume(); displayChats(); } @Override public View getView() { final Button sendChatButton = (Button) rootView.findViewById(R.id.text_send); final EditText chatEntryWindow = (EditText) rootView.findViewById(R.id.chat_text_compose); // Check to see if the text entry field is empty. If it is empty, disable the "Send" button. chatEntryWindow.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() != 0){ sendChatButton.setEnabled(true); } else { sendChatButton.setEnabled(false); } } @Override public void afterTextChanged(Editable s) {} }); // Send the chat if(sendChatButton != null) { sendChatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Date rightNow = new Date(); SimpleDateFormat timeSDF = new SimpleDateFormat(Constants.SIMPLE_TIME, Locale.US); SimpleDateFormat dateSDF = new SimpleDateFormat(Constants.SIMPLE_DATE, Locale.US); SharedPreferences myAppPreferences = getContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); String message = chatEntryWindow.getText().toString(); String username = myAppPreferences.getString("username", Constants.TABLET_ID); Message myMessage = new Message(true, username, message, 0, dateSDF.format(rightNow), timeSDF.format(rightNow)); if(!message.equals("")){ LogChat logChat = new LogChat(getActivity()); logChat.addNewMessage(myMessage); new SendChat(getActivity(), message, username).execute(); chatEntryWindow.setText(""); sendChatButton.setEnabled(false); if(v != null){ InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } displayChats(); } } }); } return super.getView(); } public void displayChats(){ DatabaseHelper myDBHelper = new DatabaseHelper(getActivity()); final Cursor chatsCursor = myDBHelper.getChatsCursor(); String[] fromColumns = {"messageInfo","messageText"}; int[] toViews = {R.id.chat_information, R.id.chat_message}; SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.line_of_chat, chatsCursor, fromColumns, toViews, 0); ListView myListView = (ListView) rootView.findViewById(R.id.chat_text_display); // Draw the list myListView.setAdapter(simpleCursorAdapter); myDBHelper.close(); } } 

Utilice CustomAdapter como necesitará establecer registerForContextMenu() en sus dos TextViews como sigue.

 registerForContextMenu(holder.chatMessage); registerForContextMenu(holder.chatInfo); 

Use onCreateContextMenu para crear un context menu y para mostrar el texto seleccionado

 @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) { TextView textView = (TextView) view; menu.setHeaderTitle(textView.getText()).add(0, 0, 0, R.string.menu_copy_to_clipboard); clipBoardText = textView.getText().toString(); } 

Y utilice onContextItemSelected para copiar el texto en el clip board

 @Override public boolean onContextItemSelected(MenuItem item) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); final android.content.ClipData clipData = android.content.ClipData .newPlainText("label", clipBoardText); clipboardManager.setPrimaryClip(clipData); } else { ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(clipBoardText); } return true; } 

He intentado con esto. Usted tiene que hacer un clic largo en el textView desde el que desea que el texto que se va a copiar. Muestra un dialog y después de hacer clic en copiar texto, el texto se copiará en el clipboard . Puedes pegarlo donde quieras. El ejemplo que he intentado está aquí .

Se espera un solo clic. Android no se hilight en un solo clic.

Ingresa al modo de acción para copiar y pegar. Un modo de acción es un estado de una actividad en la que la barra de herramientas cambia para un conjunto de comandos de contexto (en este caso copiar / pegar comandos). Parece como si estuvieras entrando y luego saliendo inmediatamente, posiblemente porque estás perdiendo el foco de otro elemento.

Tal vez debería usar registerForContextMenu(yourTextView); , Su TextView se registrará para recibir eventos del menú contextual. Y usted podrá conseguir el texto de su textview en el sujetapapeles usando OnCreateContextMenu .

  @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { //user has long pressed your TextView menu.add(0, v.getId(), 0, "your text...copy blbblaba"); //cast the received View to TextView so that you can get its text TextView yourTextView = (TextView) v; //place your TextView's text in clipboard ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(yourTextView.getText()); } 

Como un FYI, por si acaso alguien más viene buscando una respuesta.

Dejé de intentarlo de esta manera, usando "android: textIsSelectable = 'true'", y fue otra ruta. En lugar de eso, establecí un "onItemLongClickListener ()" y utilicé el ClipboardManager para agarrar el texto dentro del chat:

 public void displayChats(){ final Context context = getContext(); final ClipboardManager clipboardManager = (ClipboardManager)context.getSystemService(context.CLIPBOARD_SERVICE); DatabaseHelper myDBHelper = new DatabaseHelper(getActivity()); final Cursor chatsCursor = myDBHelper.getChatsCursor(); String[] fromColumns = {"messageInfo","messageText"}; int[] toViews = {R.id.chat_information, R.id.chat_message}; SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.line_of_chat, chatsCursor, fromColumns, toViews, 0); ListView myListView = (ListView) rootView.findViewById(R.id.chat_text_display); // Draw the list myListView.setAdapter(simpleCursorAdapter); myListView.setOnLongClickListener(new AdapterView.OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){ TextView chatText = (TextView)view.findViewById(R.id.chat_message); ClipData clipData = ClipData.newPlainText("copied chat", chatText.getText.toString()); if(clipboardManager.hasPrimaryClip()){ Toast.makeText(this, "copied text", Toast.LENGTH_LONG).show(); } return false; } }); myDBHelper.close(); } 
  • ¿Cómo puedo agregar efecto de degradado al color de fondo de TextView en un ListView?
  • En Android cómo cambiar el color de una letra / carácter en particular que se está buscando dentro de la lista
  • Android - Extensible TextView con animación
  • Mostrar imagen en TextView
  • Cómo hacer que un TextView parezca un encabezado PreferenciaCategoría de un ajuste
  • Cómo convertir SpannedString a Spannable
  • Cómo deshabilitar el TextView maxLines mediante programación?
  • ¿Hay una manera de ocultar texto en un TextView?
  • Cómo hacer que la vista de texto parpadee
  • Hacer TextView Scrollable en Android mediante programación
  • Android: establece el texto en TextView
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.