如何使用CustomAdapter在ListView上设置OnItemClickListener

时间:2017-02-18 10:39:26

标签: android listview adapter

我显示了数据库中的学生列表,显示了Student_Roll_no,Student_Name和Student_ID字段。 使用TextView显示Student_Roll_no和Student_Name,并显示带有复选框的Student_ID id。 现在我想设置代码,当我点击列表时,应检查该特定行的复选框,但listview没有响应OnItemClickListener函数,因为我点击了当我点击时没有出现的吐司在名单上。

为了糟糕的英语而烦恼

activity_attendence.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_attendence"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.tejas.paras.bpibs.Attendence"
android:orientation="vertical">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/roll"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:text="Roll"
        android:layout_weight=".1"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:text="Name"
        android:layout_weight=".6"
        android:textColor="#000000" />

    <TextView
        android:text="Present"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView26"
        android:layout_weight=".2"
        android:textColor="#000000" />

</LinearLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="#000000"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"></LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="375dp"
        android:id="@+id/listview"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_weight="1.10" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:text="Save Attendence"
            android:layout_width="match_parent"
            android:background="@drawable/buttonlayout2"
            android:textColor="#FFFFFF"
            android:layout_height="wrap_content"
            android:id="@+id/button5" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>

Attendence.java

package com.tejas.paras.bpibs;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

public class Attendence extends AppCompatActivity{

String date, course, year,ID;
String myJSON;

private static final String TAG_RESULTS = "result";

String link;
JSONArray peoples = null;
BufferedReader bufferedReader;
String result,data;
ArrayList<HashMap<String, String>> personList;
Button b5;
ListView list,listView;
private DataModel dataModel;
private ArrayList<DataModel> dataModels;
private static CustomAdapter adapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendence);
    list=(ListView)findViewById(R.id.listview);
    b5=(Button)findViewById(R.id.button5);

    getData();

    b5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(Attendence.this,"1."+view, Toast.LENGTH_SHORT).show();
        }
    });


    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> a, View v, int position,
                                long id) {
             dataModel = dataModels.get(position);
            Toast.makeText(Attendence.this,"2.1",Toast.LENGTH_LONG).show();
             ID=dataModel.getID();
                Toast.makeText(Attendence.this,dataModel.getRoll(),Toast.LENGTH_LONG).show();

        }
    });
}


protected void showList() {
    dataModels= new ArrayList<>();

    try {

        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for (int i = 0; i < peoples.length(); i++) {
            JSONObject c = peoples.getJSONObject(i);

            dataModels.add(new DataModel(c.getString("name"),c.getString("id"),  c.getString("roll")));
        }
        adapter = new CustomAdapter(dataModels, getApplicationContext());
        list.setAdapter(adapter);

    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}


public void getData() {
    class GetDataJSON extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            try {

                link = "http://painnation.esy.es/attendence.php?date=18022017&course=MCA&year=3";
                URL url = new URL(link);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));


                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = bufferedReader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            myJSON = result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}
}

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >


<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight=".1">

    <TextView
        android:id="@+id/roll"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textStyle="bold"
        android:text="Roll"
        android:layout_weight=".1"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textStyle="bold"
        android:text="Name"
        android:layout_weight=".6"
        android:textColor="#000000" />

    <CheckBox
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/id"
        android:layout_weight=".15"
        android:textColor="#000000" />

</LinearLayout>
</LinearLayout>

CustomAdapter.java

package com.tejas.paras.bpibs;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.ArrayList;


public class CustomAdapter extends ArrayAdapter<DataModel> implements View.OnClickListener{

private ArrayList<DataModel> dataSet;
Context mContext;

private static class ViewHolder {
    TextView name;
    TextView roll;
    CheckBox id;
}

public CustomAdapter(ArrayList<DataModel> data, Context context) {
    super(context, R.layout.item_layout, data);
    this.dataSet = data;
    this.mContext=context;

}

@Override
public void onClick(View v) {

    int position=(Integer) v.getTag();
    Object object= getItem(position);
    DataModel dataModel=(DataModel)object;

}

private int lastPosition = -1;

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

    DataModel dataModel = getItem(position);

    ViewHolder viewHolder;

    final View result;

    if (convertView == null) {

        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.item_layout, parent, false);
        viewHolder.name = (TextView) convertView.findViewById(R.id.name);
        viewHolder.roll = (TextView) convertView.findViewById(R.id.roll);
        viewHolder.id=(CheckBox) convertView.findViewById(R.id.id);


        result=convertView;

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
        result=convertView;
    }
    lastPosition = position;
    viewHolder.name.setText(dataModel.getName());
    viewHolder.roll.setText(dataModel.getRoll());
    viewHolder.id.setText(dataModel.getID());

    return convertView;
}
}

DataModel.java

package com.tejas.paras.bpibs;

public class DataModel {

String roll;
String name;
String id;

public DataModel(String name1, String id1, String roll1) {
    this.name=name1;
    this.id=id1;
    this.roll=roll1;
}

public String getName() {
    return name;
}

public String getID() {
    return id;
}

public String getRoll() {
    return roll;
}
}

Attendence.php文件和数据库托管在免费托管Web服务器(Hostinger)上。你可以用。检查数据库输出 http://painnation.esy.es/attendence.php?date=18022017&course=MCA&year=3

Output Screen

来自服务器的数据是以json格式获取的。请注释要执行的代码,单击listview检查复选框。

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您应该将android:focusable="false"放在item_layout.xml中以获取复选框,然后onItemClickListener响应。对于复选框,您需要将变量放在DataModel中,android使其成为true或false并在listview中更改put adapter.notifyDataSetChanged

<CheckBox
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/id" 
        android:layout_weight=".15"
        android:focusable="false"
        android:textColor="#000000" />