12 January 2017

Android: ListView Click ImageButton Sử Dụng BaseAdapter & Interface (Android Studio)

activity_main.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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.example.lonely.listviewbaseadapter.MainActivity">

    <ImageView
        android:id="@+id/iv_avatar_top"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:background="#2400ccb1"
        android:layout_centerHorizontal="true"
        android:src="@drawable/person_avartar" />

    <EditText
        android:id="@+id/ed_name_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:textColor="#9e0018"
        android:textSize="25sp"
        android:background="#2400ccb1"
        android:gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_below="@id/iv_avatar_top"
        />

    <ListView
        android:id="@+id/lv_contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/ed_name_top" />
</RelativeLayout>
item_contact.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_avatar"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/avatar1" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="13dp"
        android:layout_toRightOf="@id/iv_avatar"
        android:text="Ewin Rommel"
        android:textColor="#000350"
        android:textSize="17sp" />

    <TextView
        android:id="@+id/tv_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_name"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@id/iv_avatar"
        android:text="098372323"
        android:textColor="#ff0008"
        android:textSize="19sp" />

    <LinearLayout
        android:id="@+id/ln_right_001"
        android:layout_alignParentRight="true"
        android:layout_marginTop="18dp"
        android:orientation="horizontal"
        android:layout_width="100dp"
        android:layout_height="wrap_content">

        <ImageButton
            android:id="@+id/iv_btn_edit"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:src="@drawable/ic_action_edit" />

        <ImageButton
            android:id="@+id/iv_btn_call"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:src="@drawable/ic_action_call" />
    </LinearLayout>
</RelativeLayout>
MainActivity.java
Java Android 2017
package com.example.lonely.listviewbaseadapter;

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

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IOnChildItemClick{
    private ListView lvContact;
    private List<ContactModel> listContact = new ArrayList<>();
    private ContactAdapter mAdapter;
    private TextView edNameTop;
    private ImageView ivAvatarTop;

    //Khi làm việc với ListView thường sẽ có 3 bước chính
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Bước 1: Tạo data
        initData();
        initView();

        //Bước 2: Tạo adapter ở ví dụ này chúng ta tự tạo một Adapter không phụ thuộc vào Adapter có sẵn
        mAdapter = new ContactAdapter(listContact, this);
        mAdapter.registerChildItemClick(this);
        //Bước 3: Tạo ListView Set adapter vào ListView
        lvContact.setAdapter(mAdapter);

        //Bắt sự kiện click vào ListView  dòng bao nhiêu nhận biết thông qua position
        lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactModel contactModel = listContact.get(position);
                Toast.makeText(MainActivity.this, contactModel.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void initView(){
        lvContact = (ListView) findViewById(R.id.lv_contact);
        edNameTop = (TextView) findViewById(R.id.ed_name_top);
        ivAvatarTop = (ImageView) findViewById(R.id.iv_avatar_top);
    }

    public void initData() {
        listContact.add(new ContactModel("Dương Triệu Vũ", "098987923521", R.drawable.avatar1));
        listContact.add(new ContactModel("Dương Minh Ngọc", "098987923522", R.drawable.avatar2));
        listContact.add(new ContactModel("Dương Hồng Tuyền", "098987923524", R.drawable.avatar3));
        listContact.add(new ContactModel("Dương Tử Quỳnh", "098987923525", R.drawable.avatar4));
        listContact.add(new ContactModel("Dương Anh Khang", "098987923521", R.drawable.avatar1));
        listContact.add(new ContactModel("Đinh Diệu Linh", "098987923525", R.drawable.avatar2));
        listContact.add(new ContactModel("Nguyễn Ngọc Anh", "098987923521", R.drawable.avatar3));
        listContact.add(new ContactModel("Triệu Tài Vinh", "098987923522", R.drawable.avatar4));
        listContact.add(new ContactModel("Hoàng Văn Kiên", "098987923524", R.drawable.avatar1));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdapter.unRegisterChildItemClick();
    }

    @Override
    public void onItemChildClick(int position) {
        ContactModel c = listContact.get(position);
        edNameTop.setText(c.getName());
        ivAvatarTop.setImageResource(c.getImage());
    }
}
ContactModel.java
Java Android 2017
package com.example.lonely.listviewbaseadapter;

/**
 * Created by Lonely on 1/12/2017.
 */

public class ContactModel {
    private String name;
    private String phone;
    private int image;

    public ContactModel(String name, String phone, int image) {
        this.phone = phone;
        this.image = image;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}
ContactAdapter.java
Java Android 2017
package com.example.lonely.listviewbaseadapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Lonely on 1/12/2017.
 */

public class ContactAdapter extends BaseAdapter {

    private List<ContactModel> listContact;
    private Context mContext;
    private IOnChildItemClick iOnChildItemClick;

    public void registerChildItemClick(IOnChildItemClick iOnChildItemClick) {
        this.iOnChildItemClick = iOnChildItemClick;
    }

    public void unRegisterChildItemClick() {
        this.iOnChildItemClick = null;
    }

    public ContactAdapter(List<ContactModel> listContact, Context mContext) {
        this.listContact = listContact;
        this.mContext = mContext;
    }

    @Override
    public int getCount() {
        return listContact.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            convertView = inflater.inflate(R.layout.item_contact, null);

            ViewHolder holder = new ViewHolder();
            holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
            holder.ivAvatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
            holder.ivBtnEdit = (ImageView) convertView.findViewById(R.id.iv_btn_edit);
            holder.ivBtnCall = (ImageView) convertView.findViewById(R.id.iv_btn_call);
            convertView.setTag(holder);
        }
        ViewHolder holder = (ViewHolder) convertView.getTag();
        ContactModel model = listContact.get(position);
        holder.tvName.setText(model.getName());
        holder.tvPhone.setText(model.getPhone());
        holder.ivAvatar.setImageResource(model.getImage());
        //Lắng nghe sự kiện click vào icon edit 
        //dùng interface để gửi position qua MainActivity.java để setText & setImageResource
        //cách làm này có thể rất nhiều người chưa biết và tất cả các ví dụ trên internet chưa đề cập vấn đề này
        holder.ivBtnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iOnChildItemClick.onItemChildClick(position);
            }
        });
        //Lắng nghe sự kiện click vào icon call
        holder.ivBtnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCall(position);
            }
        });

        return convertView;
    }

    //Tạo một lần duy nhất để tránh việc tạo nhiều lần làm chậm ứng dụng
    static class ViewHolder {
        TextView tvName;
        TextView tvPhone;
        ImageView ivAvatar;
        ImageView ivBtnEdit;
        ImageView ivBtnCall;
    }

    private void onCall(int position) {
        ContactModel contactModel = listContact.get(position);
        //======ACTION_CALL======//
        Intent intent = new Intent(android.content.Intent.ACTION_CALL, Uri.parse("tel:" + contactModel.getPhone()));
        //Nếu dùng ACTION_CALL khi startActivity(intent) nó generate (sinh ra) phần chữ TO DO màu đen nhạt phía dưới
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //=====ACTION_DIAL======//
        //Còn nếu sử dụng ACTION_DIAL thì hoàn toàn không có như phần ACTION_CALL
        //Intent intent = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:"+contactModel.getPhone()));
        mContext.startActivity(intent);
    }

}
IOnChildItemClick.java
Java Android 2017
package com.example.lonely.listviewbaseadapter;

/**
 * Created by Lonely on 1/12/2017.
 */
//Interface nó rất linh hoạt nếu chúng ta biết sử dụng nó vì với này
public interface IOnChildItemClick {
    void onItemChildClick(int position);
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang