setOnItemClickListener用于在没有适配器的情况下扩展ListActivity的活动

时间:2015-10-09 09:56:49

标签: android listview android-arrayadapter

我想为下面提到的listview实现一个setOnItemClickListener。 在将字符串数组项目显示到listview时,代码可以正常工作,但我想在用户点击并在longclick上执行某些操作。

public class MainActivity extends ListActivity{

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] plainStrings = getResources().getStringArray(R.array.myarray);
    Spanned[] htmlStrings = new Spanned[plainStrings.length];
    for(int i = 0 ; i < plainStrings.length; i++) {
        htmlStrings[i] = Html.fromHtml(plainStrings[i]);
    }
setListAdapter(new ArrayAdapter<CharSequence>(this,R.layout.items, htmlStrings));
 }

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:isScrollContainer="true"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:scrollbarStyle="insideOverlay">

 <ListView
   android:id="@android:id/list"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:clickable="true"
   android:dividerHeight="3dp"/>
</LinearLayout>

items.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

2 个答案:

答案 0 :(得分:0)

ListActivity有自己的受保护方法onListItemClick,您可以覆盖它以获取行点击的事件

答案 1 :(得分:0)

正常点击:

      listView.setOnItemClickListener(new OnItemClickListener() {
                        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        //Do whatever you want                 

Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
                        }
                    });

长按:

 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {
//Do whatever you want
     Toast.makeText(getApplicationContext(),"Long Clicked",Toast.LENGTH_SHORT).show();
        });
    }