Ponglang Petrung
Jan 17 · 7 min read
  • สามารถคลิ๊กแต่ละแถวของ ListView ได้
  • รู้จักกับ ArrayAdapter
package com.devahoy.demo.basiclistview;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.devahoy.demo.basiclistview;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<?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_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.exmple.myfirstapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/list_item_example"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</LinearLayout>
package com.exmple.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] myMenus = new String[]{
"Facebook", "Youtube", "Line", "Instagram", "Twitter"
};
ListView lsv = (ListView) findViewById(R.id.list_item_example);
ArrayAdapter<String> arrAdt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myMenus);
lsv.setAdapter(arrAdt);
lsv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String UserSelected = ((TextView) arg1).getText().toString();
Toast.makeText(getApplicationContext(), UserSelected, Toast.LENGTH_SHORT).show();
}
});
}
}
lsv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String UserSelected = ((TextView) arg1).getText().toString();
Toast.makeText(getApplicationContext(), UserSelected, Toast.LENGTH_SHORT).show();
}
});
  • มี LayoutManager คอยควบคุม element ต่างๆ ได้มากขึ้น
  • ใช้ ViewHolder Pattern ซึ่งช่วยในเรื่องการ reuse อย่างมาก
  • เหมาะสำหรับ ListView ที่ข้อมูลมีการเปลี่ยนแปลงบ่อยๆ
  • มี Animation ด้วย
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support:recyclerview-v7:+"
}
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.exmple.recyclerviewkukps"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support:recyclerview-v7:+"
}
}

สร้างโมเดล Player

ขั้นตอนนี้ ต้องการให้แสดงชื่อนักฟุตบอล และสโมสรที่สังกัด เพราะฉะนั้น ก็เลยสร้าง class ง่ายๆแบบนี้

package com.exmple.recyclerviewkukps;
/**
* Created by Pongploy2017 on 1/2/2018.
*/
public class Player {
private String name;
private String club;
public Player(String name, String club) {
this.name = name;
this.club = club;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClub() {
return club;
}
public void setClub(String club) {
this.club = club;
}
}

CustomAdapter

ทำการสร้าง CustomAdapter โดยต้องทำการ extends คลาส RecyclerView.Adapter แบบนี้

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name"
android:textColor="#ffee1789"
android:layout_marginRight="48dp" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0071ff"
android:id="@+id/club" />
</LinearLayout>
package layout;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
* Created by Pongploy2017 on 1/2/2018.
*/
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<Player> mPlayers;
private Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mName;
public TextView mClub;
public ViewHolder(View view) {
super(view);
mName = (TextView) view.findViewById(R.id.name);
mClub = (TextView) view.findViewById(R.id.club);
}
}
public CustomAdapter(Context context, List<Player> dataset) {
mPlayers = dataset;
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext)
.inflate(R.layout.recycler_view_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Player player = mPlayers.get(position);
viewHolder.mName.setText(player.getName());
viewHolder.mClub.setText(player.getClub());
}
@Override
public int getItemCount() {
return mPlayers.size();
}
}เมธอดที่สำคัญที่ทำการ override มีด้วยกันดังนี้
  • onBindViewHolder() : เมธอดนี้ก็ถูกเรียกโดย LayoutManager เหมือนกัน เอาไว้สำหรับ เซทค่า dataset ของใส่ไปยังพวก View ต่างๆ เช่นใส่ค่าให้ TextView, ImageView
  • getItemCount() : ส่งค่าจำนวน item ของ dataset
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
package com.exmple.recyclerviewkukps;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CustomAdapter(this, initPlayer());
mRecyclerView.setAdapter(mAdapter);
}
private List<Player> initPlayer() {
Player messi = new Player("Leonel Missi", "Barcelona");
Player ronaldo = new Player("Cristiano Ronaldo", "Real Madrid");
Player suarez = new Player("Luis Suarez", "Liverpool");
List<Player> dataset = new ArrayList<Player>();
dataset.add(messi);
dataset.add(ronaldo);
dataset.add(suarez);
return dataset;
}

}

Android Open Source Projects [inclusion] [SUM] [Join user groups] There is a problem with Android projects and want to give answers. What's new or want to update the robot continuously. Can join. Line: po56789 or inbox on the page, come to join, please just !!!!
Thank you

Ponglang Petrung

Written by

Senior Android Devaloper Freewill Solutions Co.,Ltd.) FB Group https://www.facebook.com/groups/883546485084033/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade