jjzjj

android - 每当我尝试选择文本时,为什么我的 Android UI 表现不稳定?

coder 2023-11-19 原文

我正在开发一款 Android 应用(API 15 及以下版本)。在我的 UI 中,我有一个 TextView 元素,我希望人们能够从中选择和复制。这是我的元素的样子:

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

此 TextView 位于一个 ListView 中,该 ListView 填充了一个 SimpleCursorAdapter。这个 ListView 看起来像这样:

<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"/>

ListView 在 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>

每当我尝试单击 chat_info 或 chat_message 中的文本时,都没有任何反应。但是,每当我尝试双击文本时:

  1. 我的整个用户界面向下移动
  2. “工具栏”出现在屏幕顶部
  3. “工具栏”立即消失,我的显示恢复原状

在“工具栏”中,这是我看到的:

看起来是复制对话框,但马上就没了。

我可以在带有 android:textIsSelectable="true" 的 LinearLayout 中插入一个“独立”的 TextView,并且复制对话框可以正常工作;这意味着在我选择“复制”之前它将一直可见。

我可以提供的最后一条信息是,我的 LinearLayout 位于一个选项卡式 Activity 中,该 Activity 使用带有 ViewPager 的 fragment 。我只是不明白这是怎么回事,因为就像我说的那样,我可以在 LinearLayout 中添加另一个元素(例如 TextView),并且“复制”对话框可以完美运行。我想我会添加这篇文章以完全清楚。

我只想选择 chat_info 或 chat_message 中的文本,这样我就可以将文本复制并粘贴到其他地方。

有什么想法吗?

新信息!!!

当我选择“chat_text_compose”EditText 中的文本时,复制工具栏正常出现。此时,我可以成功地选择我的 TextView 区域中的文本。很奇怪。

更新:控制此布局的代码

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

最佳答案

使用 CustomAdapter,因为您需要将 registerForContextMenu() 设置为您的两个 TextViews,如下所示。

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

使用onCreateContextMenu 创建上下文菜单 并显示所选文本

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

并使用onContextItemSelected 将文本复制到剪贴板

@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;
}

我试过这个。您必须长按要从中复制文本的 textView。它显示一个对话框,点击复制文本后,文本将被复制到剪贴板。您可以将其粘贴到任何您想要的地方。我试过的例子是 here .

关于android - 每当我尝试选择文本时,为什么我的 Android UI 表现不稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398937/

有关android - 每当我尝试选择文本时,为什么我的 Android UI 表现不稳定?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  4. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  9. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐