如何为列表视图实现Long Click Listener

时间:2014-04-20 07:26:40

标签: android onlongclicklistener

我在各种论坛上搜索了正确的答案,但对我来说没有任何作用。目前我在私人课程MyDiary中有这段代码:

ListView list = new ListView(Monday.this);
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    new EditListItemDialog(view.getContext()).show();

                return true;       
            }
        });

它不会返回错误,但EditListItemDialog无法打开。我在这里缺少什么?

修改

EditListItemDialog的代码:

package com.example.classorganizer;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

class EditListItemDialog extends Dialog implements View.OnClickListener {

private View editText;

public EditListItemDialog(Context context) {
    super(context);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
    View btnOk = findViewById(R.id.button_ok);
    editText = findViewById(R.id.edit_text);
    btnOk.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    ((TextView) editText).getText().toString();//here is your updated(or not updated) text
    dismiss();
}
}

XML文件:

     <ListView
        android:layout_width="fill_parent"
                        android:gravity="center"
        android:layout_height="fill_parent"
    android:id="@android:id/list"
        android:longClickable="true"
         >

    </ListView>

创建行:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignLeft="@+id/name"
android:layout_below="@+id/name"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="0dip">
<TextView android:textSize="16dip"
                                android:layout_width="wrap_content"
                            android:layout_height="29dp"
                            android:layout_marginTop="0dp"
                            android:id="@+id/name"
                            android:layout_marginRight="4dp"
                            android:text="Diary Title"
                            android:textStyle="bold"
                            android:longClickable="true" />



</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

假设您使用ListActivity,则应更改以下行(来自您的第一个代码块)...

ListView list = new ListView(Monday.this);

......待......

ListView list = getListView();

然后您可以为其设置监听器。