java - Android中如何从ListView和Adapter中获取选中的文本?

标签 java android eclipse listview android-adapter

我花了几个小时试图解决这个问题,虽然我已经接近了,但我没有得到我需要的结果。我有一个消息传递应用程序,它有一个自定义适配器和一个包含大约 5 个 TextView 的 ListView 。我的问题是当用户长按消息时检索文本。在尝试了各种方法之后,我最接近的是:

        mListView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener
            (){


    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {

        final String test = ((TextView)v).getText().toString();
        Log.i(TAG, "Received: " + test);


        return true;

        }
            }); 

关于此代码的愚蠢(读:令人沮丧)部分是,单击时它会成功运行大约 3-4 次,但之后它会强制关闭我的应用程序。我得到的错误是:

FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to  android.widget.TextView
 at android.widget.AbsListView.performLongPress(AbsListView.java:3347)
 at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:3294)
 at android.os.Handler.handleCallback(Handler.java:725)

奇怪的是,我前几次成功获得了正确的消息字符串,然后它就不想工作了。查找错误后,我尝试多次清理项目、删除 R.java 文件并关闭 Eclipse,但没有任何效果。

我也尝试过使用消息的位置编号。在获取消息的位置号时,应用程序永远不会强制关闭,但是我无法让它获取附加到该位置消息的字符串。错误是关于尝试从整数转换为字符串:

String test = ((EditText)av.getItemAtPosition(pos)).getText().toString();

我的 xml 文件包含:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal" >

<LinearLayout
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_margin="20dip"
    android:background="@drawable/bubble_yellow"
    android:gravity="left"
    android:orientation="vertical"
    android:visibility="invisible" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:paddingBottom="1dip"
        android:paddingLeft="15dip"
        android:paddingRight="20dip"
        android:paddingTop="1dip"
        android:singleLine="false"
        android:text="Large Text"
        android:longClickable="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:gravity="right"
        android:paddingRight="20dip"
        android:longClickable="true"
        android:text="TextView" />
</LinearLayout>

<LinearLayout
    android:id="@+id/right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_margin="20dip"
    android:background="@drawable/bubble_green"
    android:orientation="vertical"
    android:visibility="invisible" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="1dip"
        android:paddingLeft="15dip"
        android:paddingRight="20dip"
        android:paddingTop="1dip"
        android:singleLine="false"
        android:longClickable="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:gravity="right"
        android:longClickable="true"
        android:paddingRight="20dip"
        android:text="TextView" />
   </LinearLayout>

 </RelativeLayout>

更新 1:添加了请求的 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background2"
android:orientation="vertical" >

<ListView
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:divider="@null"
    android:dividerHeight="0dp"
    android:longClickable="true"
    android:stackFromBottom="true" >
</ListView>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp" />

<LinearLayout
    android:id="@+id/sendMsgLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="20dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/messageText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_weight="1"
        android:hint="Type Message"
        android:inputType="textCapSentences|textMultiLine"
        android:textColor="#FFFFFF"
        android:maxLines="3" >

        <requestFocus />
    </EditText>

    <ImageView
        android:id="@+id/imageSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:src="@drawable/send512" />
</LinearLayout>

</LinearLayout>

更新2:我的适配器包含以下内容:

        ViewHolder viewHolder;
 MessageModel array = data.get(position);
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.message_item, null);
        viewHolder.left =(LinearLayout)convertView.findViewById(R.id.left);
        viewHolder.right =(LinearLayout)convertView.findViewById(R.id.right);
        viewHolder.txt1 = (TextView) convertView
                .findViewById(R.id.textView1);
        viewHolder.txt3 = (TextView) convertView
                .findViewById(R.id.textView3);
        viewHolder.txt2 = (TextView) convertView
                .findViewById(R.id.textView2);
        viewHolder.txt4 = (TextView) convertView
                .findViewById(R.id.textView4);

        convertView.setTag(viewHolder);

更新3:我尽力遵循@MDragon00的建议,不幸的是我的应用程序在长按时仍然崩溃。我现在有:

        mListView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener
            (){


    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {


        TextView textView1 = (TextView) v.findViewById(R.id.textView1);
        TextView textView2 = (TextView) v.findViewById(R.id.textView2);
        TextView textView3 = (TextView) v.findViewById(R.id.textView3);
        TextView textView4 = (TextView) v.findViewById(R.id.textView4);

        View.OnLongClickListener listener = new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {

                TextView textView = (TextView) v;
                String text = textView.getText().toString();
                Log.i(TAG, "Text Selected = " + text);
                return false;
            }
        };

        textView1.setOnLongClickListener(listener);
        textView2.setOnLongClickListener(listener);
        textView3.setOnLongClickListener(listener);
        textView4.setOnLongClickListener(listener);

        return true;

        }
            }); 



}

最佳答案

onItemLongClick中各个参数作用的说明:http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html

这里的问题是 av整个 ListView,而 v整个行。您的行不仅仅包含 TextView,因此您无法将其转换为 TextView。换句话说,

final String test = ((TextView)v).getText().toString();

这不是一个好主意,因为父 View 是一个RelativeLayout。更好的解决方案是执行以下操作:

TextView textView = (TextView) v.findViewById(R.id.idOfTextView);
String text = textView.getText().toString();

作为一个小建议,听起来您只想简单地单击该项目,而不是长时间单击它。如果适合您的需要,请使用 OnItemClickListener 而不是 OnItemLongClickListener。

编辑: 根据您的评论,用户将在某个抽象行中的多个 TextView 中单击/点击某个 TextView,并且您想要获取这四个 TextView 之一。

为此,您需要在每个 TextView 上有一个新的监听器。如果没有看到您的适配器,我无法给出确切的答案,但是当您膨胀/获取行 View 以提供给适配器中的 ListView 时,请将 OnClickListener 设置为 TextViews。例如一些伪代码:

// Get the textViews, to assign a listener to them
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (Textview) v.findViewById(R.id.textView2);
..... // Etc and so on

// Create this listener anywhere, including via making the adapter/class
    // implement the listener and passing it in instead
View.OnClickListener listener = new View.OnClickListener(
    @Override
    public void onClick(View v) {
        // Get the view as a TextView, as this will only be used
            // with TextViews, so the only view to be passed
            // will be Textviews
        TextView textView = (TextView) v;

        // Do whatever with that text, or however you want to use the view
        String text = textView.getText().toString();
        someFunction(text);
    }
);

textView1.setOnClickListener(listener);
textView2.setOnClickListener(listener);
..... // Etc and so on

现在,如果您需要单击的确切行以及确切 TextView 中的文本,那么您需要使用两个监听器 [即 ListView 上的一个和 TextView 上的一个] 来获取适当的数据。

编辑希望最终:

public class TestAdapter extends BaseAdapter {
    Context mContext;

    public TestAdapter (Context context, Data someData) {
        this.mContext = context;

        // Set up the data for your listView however
    }
    @Override
    public int getCount() {
        return howManyRows;
    }

    @Override
    public Object getItem(int position) {
        return objectAtPosition;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    } // Unnecessary, unless using databases

    // The listener for the textViews, feel free to use different listeners
    View.OnClickListener TextViewListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get the view as a TextView, as this will only be used
            // with TextViews, so the only view to be passed
            // will be Textviews
            TextView textView = (TextView) v;

            // Do whatever with that text, or however you want to use the view
            String text = textView.getText().toString();
            someFunction(text);
        }
    };

    // Using the efficient pattern for recycling the views rather than using
    // findViewById repeatedly
    public static class ViewHolder{
        public TextView textView1;
        public TextView textView2;
        public TextView textView3;
        public TextView textView4;

        // And any other view that's part of the row view that you need
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = null;
        ViewHolder holder;

        if(convertView == null) {
            // Then gotta set up this row for the first time
            LayoutInflater inflater =
                    (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.row_layout.xml, parent, false);

            // Create a ViewHolder to save all the different parts of the row
            holder = new ViewHolder();
            holder.textView1 = (TextView) row.findViewById(R.id.textView1);
            holder.textView2 = (TextView) row.findViewById(R.id.textView2);
            holder.textView3 = (TextView) row.findViewById(R.id.textView3);
            holder.textView4 = (TextView) row.findViewById(R.id.textView4);

            // Make the row reuse the ViewHolder
            row.setTag(holder);
        }
        else { // Otherwise, use the recycled view
            row = convertView;
            holder = (ViewHolder) row.getTag();
        }

        // Set the current row's Textview onClickListeners
            // Note: You MAY be able to only set these once- feel free to set that
        holder.textView1.setOnClickListener(TextViewListener);
        holder.textView2.setOnClickListener(TextViewListener);
        holder.textView3.setOnClickListener(TextViewListener);
        holder.textView4.setOnClickListener(TextViewListener);

        // Set up the rest of the views however you need
            /*.....
              ......
             */

        return row;
    }
}

关于java - Android中如何从ListView和Adapter中获取选中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26519573/

相关文章:

java - 无法更改eclipse中的jre版本

java - 通过 webclient 调用 https IP 时无法解析主机

java - 发送 session

java - 在主屏幕应用程序中禁用主页按钮?

Android 企业锁定

java - 使用嵌入式 Felix 进行调试

java - 递归地对数组中的整数求和

Java AS400 "Internal driver error"与控制台应用程序

android - 如何像垂直 Viewpager 变换一样为 RecyclerView 设置动画

java - 打开 null 分析时允许 NullPointerException 的最佳方法