如何使列表视图项可点击?

时间:2014-10-31 06:34:58

标签: java android xml

我必须使列表视图项可点击,即开始活动。我使用以下代码。我不知道如何继续。

package org.example.androidsdk.demo;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

    String [] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.myArray);

        /*
         * Assign the name array to that adapter and also choose a simple layout
         * for the list items
         */
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

5 个答案:

答案 0 :(得分:1)

在您的onListItemClick

中覆盖Activity
 @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
       String item = (String) getListAdapter().getItem(position);
       Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
   }

答案 1 :(得分:1)

转到此链接并学习如何处理ListView http://wiresareobsolete.com/2011/08/clickable-zones-in-listview-items/

答案 2 :(得分:0)

您需要实施OnItemClickListener

并致电getListView().setOnItemClickListener(this)

最后,在覆盖onItemClick方法中做你想做的事。

答案 3 :(得分:0)

尝试以下代码: -

listView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) {
    Toast.makeText(getApplicationContext(),
      "Click ListItem Number " + position, Toast.LENGTH_LONG)
      .show();
  }
}); 

请阅读以下链接以获取更多信息: -

http://www.vogella.com/tutorials/AndroidListView/article.html

http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90

答案 4 :(得分:0)

覆盖onListItemClick并在其中编写您的活动开放代码。

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
      Intent i = new Intent(this,MyClass.class);
      startActivity(i);
   }