带有 onClick 项目的 Android ListView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21295328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:18:29  来源:igfitidea点击:

Android ListView with onClick items

androidlistviewmethodsandroid-activityelements

提问by Agustín

I'm a new programmer and new in Android. I'm using this example http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/and it works great.

我是一名新程序员,也是 Android 新手。我正在使用这个例子http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/并且效果很好。

Now I want to make the items (Dell, Samsung Galaxy S3, etc) to call a function to open a new activity with different information each.

现在我想让项目(戴尔、三星 Galaxy S3 等)调用一个函数来打开一个具有不同信息的新活动。

For example:

例如:

If I touch Dell, a new Activity has to show up showing me information about Dell. If I touch Samsung, the same thing.

如果我触摸戴尔,则必须出现一个新活动,向我显示有关戴尔的信息。如果我触摸三星,同样的事情。

I Googled but couldn't find anything helpfull, any hint? I think this is basic, but I'm new so I don't really know where to start

我用谷歌搜索但找不到任何有用的东西,有什么提示吗?我认为这是基本的,但我是新手,所以我真的不知道从哪里开始

回答by Lena Bru

In your activity, where you defined your listview

在您的活动中,您定义了列表视图

you write

你写

listview.setOnItemClickListener(new OnItemClickListener(){   
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        ItemClicked item = adapter.getItemAtPosition(position);

        Intent intent = new Intent(Activity.this,destinationActivity.class);
        //based on item add info to intent
        startActivity(intent);
    }
});

in your adapter's getItem you write

在您编写的适配器的 getItem 中

public ItemClicked getItem(int position){
    return items.get(position);
}

回答by Munna Sharma

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent i = new Intent(getActivity(), DiscussAddValu.class);
        startActivity(i);
    }
});

回答by danny117

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

你用意图开始新的活动。将数据发送到 Intent 的一种方法是传递一个在 Intent 中实现 Parcelable 的类。请注意,您正在传递课程的副本。

http://developer.android.com/reference/android/os/Parcelable.html

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

这里我有一个 onItemClick。我创建意图并将整个类放入意图中。我发送的课程已经实现了parcelable。提示:您只需要在重新创建类所需的最低限度上实现可解析。即可能是一个文件名或一些简单的东西,比如一个构造函数可以用来创建类的字符串。新活动稍后可以获取Extras,它本质上是使用其构造函数方法创建类的副本。

Here I launch the kmlreader class of my appwhen I recieve an onclick in the listview.

在这里,当我在列表视图中收到 onclick 时,我会启动我的应用程序的 kmlreader 类。

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

注意:下面的摘要是我传递的类的列表,因此 get(position) 返回类实际上它与填充列表视图的列表相同

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

稍后在新活动中,我拉出可解析的类

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

祝你好运丹尼117

回答by nKn

You should definitely extend you ArrayListAdapterand implement this in your getView()method. The second parameter (a View) should be inflated if it's value is null, take advantage of it and set it an onClickListener()just after inflating.

您绝对应该扩展您ArrayListAdapter并在您的getView()方法中实现它。如果第二个参数 (a View) 的值为 ,则应该对其进行膨胀null,利用它并onClickListener()在膨胀后将其设置为 a 。

Suposing it's called your second getView()'s parameter is called convertView:

假设它被称为你的第二个getView()参数被称为convertView

convertView.setOnClickListener(new View.OnClickListener() {
  public void onClick(final View v) {
    if (isSamsung) {
      final Intent intent = new Intent(this, SamsungInfo.class);
      startActivity(intent);
    }
    else if (...) {
      ...
    }
  }
}

If you want some info on how to extend ArrayListAdapter, I recommend this link.

如果您想了解有关如何扩展的一些信息ArrayListAdapter,我推荐此链接

回答by mohammed momn

well in your onitemClickyou will send the selected value like deal, and send it in your intent when opening new activity and in your new activity get the sent data and related to selected item will display your data

好吧,您onitemClick将发送选定的值,例如deal,并在打开新活动时按照您的意图发送它,并在您的新活动中获取发送的数据和与所选项目相关的数据将显示您的数据

to get the name from the list

list

String item = yourData.get(position).getName(); 

to set data in intent

意图设置数据

intent.putExtra("Key", item);

to get the data in second activity

在第二个活动中获取数据

getIntent().getExtras().getString("Key")

回答by ceph3us

for what kind of Hell implementing Parcelable ?

对于什么样的地狱实施 Parcelable ?

he is passing to adapter String[] so

他正在传递给适配器 String[] 所以

  • get item(String) at position
  • create intent
  • put it as extra
  • start activity
  • in activity get extra
  • 在位置获取项目(字符串)
  • 创建意图
  • 把它作为额外的
  • 开始活动
  • 在活动中得到额外的

to store product list you can use here HashMap (for example as STATIC object)

存储产品列表,您可以在此处使用 HashMap(例如作为 STATIC 对象)

example class describing product:

描述产品的示例类:

public class Product {
    private String _name;
    private String _description;
    private int _id

    public Product(String name, String description,int id) {
        _name = name;
        _desctription = description;
        _id = id;
    }

    public String getName() {
        return _name;
    }

    public String getDescription() {
        return _description;
    }
}

Product dell = new Product("dell","this is dell",1);

HashMap<String,Product> _hashMap = new HashMap<>();
_hashMap.put(dell.getName(),dell);

then u pass to adapter set of keys as:

然后你传递给适配器密钥集:

String[] productNames =  _hashMap.keySet().toArray(new String[_hashMap.size()]);

when in adapter u return view u set listener like this for example:

当在适配器中返回视图时,您可以像这样设置侦听器,例如:

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

     Context context = parent.getContext(); 

     String itemName = getItem(position)

     someView.setOnClikListener(new MyOnClickListener(context, itemName));

 }


 private class MyOnClickListener implements View.OnClickListener { 

     private  String _itemName; 
     private  Context _context

     public MyOnClickListener(Context context, String itemName) {
         _context = context;
         _itemName = itemName; 
     }

     @Override 
     public void onClick(View view) {
         //------listener onClick example method body ------
         Intent intent = new Intent(_context, SomeClassToHandleData.class);
         intent.putExtra(key_to_product_name,_itemName);
         _context.startActivity(intent);
     }
 }

then in other activity:

然后在其他活动中:

@Override 
public void onCreate(Bundle) {

    String productName = getIntent().getExtra(key_to_product_name);
    Product product = _hashMap.get(productName);

}

*key_to_product_name is a public static String to serve as key for extra

*key_to_product_name 是一个公共静态字符串,作为额外的密钥

ps. sorry for typo i was in hurry :) ps2. this shoud give you a idea how to do it ps3. when i will have more time i I'll add a detailed description

附:抱歉打错了我很着急:) ps2。这应该给你一个想法如何做到 ps3。当我有更多时间时,我会添加详细说明

MY COMMENT:

我的评论:

  • DO NOT USE ANY SWITCH STATEMENT
  • DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)
  • 不要使用任何开关语句
  • 不要为每个产品创建单独的活动(你只需要一个)

回答by kenyan_ian

I was able to go around the whole thing by replacing the context reference from thisor Context.thisto getapplicationcontext.

我能够通过替换 fromthisContext.thisto的上下文引用来解决整个问题getapplicationcontext

回答by Pascal Chidi

listview.setOnItemClickListener(new OnItemClickListener(){

//setting onclick to items in the listview.

@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){

// case 0 is the first item in the listView.

  case 0:
    intent = new Intent(Activity.this,firstActivity.class);
    break;
//case 1 is the second item in the listView.

  case 1:
    intent = new Intent(Activity.this,secondActivity.class);
    break;
 case 2:
    intent = new Intent(Activity.this,thirdActivity.class);
    break;
//add more if you have more items in listView
startActivity(intent);
}

});

回答by Arjun Atlast

listview.setOnItemClickListener(new OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
    Intent intent;
    switch(position){
      case 0:
        intent = new Intent(Activity.this,firstActivity.class);
        break;
      case 1:
        intent = new Intent(Activity.this,secondActivity.class);
        break;
     case 2:
        intent = new Intent(Activity.this,thirdActivity.class);
        break;
    //add more if you have more items in listview
   //0 is the first item 1 second and so on...
    }
    startActivity(intent);
  }

});