简体   繁体   English

Android listview项目点击

[英]Android listview item click

I'm trying to get into a listview items have different action when pressed, this action depends on a variable "state", but the problem is that all the items are in the same action, here the code: 我试图进入一个listview项目时按下时具有不同的操作,此操作取决于变量“状态”,但问题是所有项目都处于同一操作中,这里的代码:

for(int i = 0; i < json.length(); i++){
                    JSONObject c = json.getJSONObject(i);
                    // Storing  JSON item in a Variable
                    String  codigo = c.getString(TAG_CODIGO);
                    String  asignatura = c.getString(TAG_NOMBRE);
                    int  estado  = c.getInt("estado");
                    final int maxhoras = c.getInt("maxhoras");
                    final String idprogramacion = c.getString("programacionid");

                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_CODIGO, codigo);
                    map.put(TAG_NOMBRE, asignatura);

                    jsonlist.add(map);
                    list=(ListView)findViewById(R.id.lvclases);
                    ListAdapter adapter = new SimpleAdapter(Bienvenida.this, jsonlist,
                            R.layout.listview,
                            new String[] { TAG_CODIGO,TAG_NOMBRE, }, new int[] {
                            R.id.codigo, R.id.nombre,
                    });
                    list.setAdapter(adapter);
                    if(estado == 1) {
                        Log.e("estado", ""+estado);
                        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
                                i.putExtra("programacion",  idprogramacion);
                                i.putExtra("maxhoras",  maxhoras);
                                startActivity(i);
                                /*Toast toast1 = Toast.makeText(getApplicationContext(), "Correcto: el usuario existe", Toast.LENGTH_SHORT);
                                toast1.show();*/
                                //Toast.makeText(Bienvenida.this, "You Clicked at " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else{
                        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }

I am working on android studio, I appreciate the help 我正在android studio上工作,感谢您的帮助

Acually, this is not an answer to your question. 从根本上讲,这不是您问题的答案。 But after watching your code it seems that you are not implementing ListView in a correct way. 但是看完代码后,似乎您没有以正确的方式实现ListView

A simple way to work with ListView goes through following abstract steps: 使用ListView一种简单方法包括以下抽象步骤:

Make your Collection Ready -> Prepare the Adapter from the collection -> Set this adapter to ListView 准备好您的收藏集->从收藏集中准备适配器->将此适配器设置为ListView

In your case, assuming you are calling web services for getting data and your web services is responding with JSON array. 在您的情况下,假设您正在调用Web服务以获取数据,并且您的Web服务使用JSON数组进行响应。

Now, make a POJO(plain old Java object) class like: 现在,制作一个POJO(普通的旧Java对象)类,例如:

public class MyListItem{
    private String codigo;
    private String asignatura;
    private int estado;
    private int maxhoras;
    private String idprogramacion;

    public MyListItem(String codigo, String asignatura, int estado, int maxhoras, String idprogramacion){
        this.codigo = codigo;
        this.asignatura = asignatura;
        this.estado = estado;
        this.maxhoras = maxhoras;
        this.idprogramacion = idprogramacion;
    }

    // you can write getter setter methods for this
    public int get_estado(){
        return estado;
    }

    public String get_idprogramacion(){
        return idprogramacion;
    }

    public int get_maxhoras(){
        return maxhoras;
    }

    public String get_asignatura(){
        return asignatura;
    }
}

Now, prepare list like: 现在,准备清单:

ArrayList<MyListItem> mArrayList = new ArrayList<>();

for(int i = 0; i < json.length(); i++){
    JSONObject c = json.getJSONObject(i);
    mArrayList.Add(
        new MyListItem(
            c.getString(TAG_CODIGO),
            c.getString(TAG_NOMBRE),
            c.getInt("estado"),
            c.getInt("maxhoras"),
            c.getString("programacionid")
        )
    );
}

Now, you are ready with list, just pass it to your custom adapter. 现在,您已经准备好使用列表,只需将其传递给您的自定义适配器即可。 If you are not aware of preparing Custom Adapter, check this link . 如果您不知道要准备“定制适配器”,请检查此链接

Once you are ready with making custom adapter, pass the list to this adapter like: 准备好制作自定义适配器后,将列表传递给该适配器,例如:

MyCustomAdapter adapter = new MyCustomAdapter(context, mArrayList); MyCustomAdapter适配器=新的MyCustomAdapter(上下文,mArrayList);

Note: Above line strictly depends constructor of your custom adapter, say, MyCustomAdapter 注意:上一行严格取决于您的自定义适配器的构造函数,例如MyCustomAdapter

After that, you are ready with your adapter, set it to your ListView, like: 之后,就可以使用适配器了,将其设置为ListView,如下所示:

list.setAdapter(adapter);

Now, here you set the OnItemClickListener 现在,在这里设置OnItemClickListener

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
         MyListItem item = (MyListItem)parent.getItem(position);
         if(item.get_estado() == 1)
         {
             Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
             i.putExtra("programacion",  item.get_idprogramacion());
             i.putExtra("maxhoras",  item.get_maxhoras());
             startActivity(i);
         }
         else{
             Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + item.get_asignatura(), Toast.LENGTH_SHORT).show();
         }

      }
});

Hope you get what you are trying to achieve.. 希望你能得到想要的成就。

This should help you out. 这应该可以帮助您。

Instead of having two different onClickListeners(), try using only one and move your if-else block inside of the onItemClick() method 而不是使用两个不同的onClickListeners(),请尝试仅使用一个,并将if-else块移至onItemClick()方法内

 list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
         if(estado == 1) {
              Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
              i.putExtra("programacion",  idprogramacion);
              i.putExtra("maxhoras",  maxhoras);
              startActivity(i);

         } else {
                   // Do something else
         }
       }
   });

Problem is estado variable, it's global varible, so When you use listview.setOnItemClickListener(...) that mean all the item in listview will be the same action with your above code. 问题是estado变量,它是全局变量,因此,当您使用listview.setOnItemClickListener(...) ,这意味着listview所有项目将与您的上述代码具有相同的作用。

Solution is you should create your own custom adapter and then implement OnItemClickListener in your adapter , base on different states to set different actions for item . 解决方案是,您应该创建自己的custom adapter ,然后根据不同的状态在adapter实现OnItemClickListener来为item设置不同的操作。 Also you can setOnClickListener in getView() in Adapter and base on state also. 您也可以在Adapter getView()中设置setOnClickListener并基于状态。

Please refer as below : 请参考以下内容:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
     int estado = -1;
     // you should do something like this
    /* ********** */
     YourItem item = ((YourItemsData)data).get(position);
     estado = item.getState();
     /* ********** */
     if(estado == 1) {
          Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
          i.putExtra("programacion",  idprogramacion);
          i.putExtra("maxhoras",  maxhoras);
          startActivity(i);

     } else {
               // Do something else
     }
   }

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM