This article is mainly to record the use of advanced control ListView and CardView and matters needing attention, although at present have used RecyclerView instead of ListView but it is necessary to understand the principle and optimization. About the principle of ListView and the real sense of optimization in the back will be dedicated to write an article to tell about, this article only about its specific use and must be optimized. As for the CardView is actually used more, you can see my small Demo implementation effect is still very good! Finally, some solutions to Android screen adaptation problems are involved.

ListView

Displays a vertically-scrollable collection of views, where each view is positioned immediatelybelow the previous view in the list. For a more modern, flexible, and performant approach to displaying lists, use android.support.v7.widget.RecyclerView.

Basic use of ListView

Use ListView as follows:

Create a ListView for each row. Create a Layout for each row. Create a view for each row

The item layout file item_app_list.xml

<? The 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:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="horizontal"> <ImageView android:id="@+id/app_icon_iv" android:src="@mipmap/ic_launcher" android:layout_width="40dp" android:layout_height="40dp"/> <TextView android:id="@+id/app_name_tv" android:textSize="20sp" android:paddingLeft="10dp" android:gravity="center_vertical" android:text="@string/app_name" android:layout_width="match_parent" android:layout_height="40dp"/> </LinearLayout>Copy the code

AppListActivity.java

public class AppListActivity extends AppCompatActivity { private List<String> appNameList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); ListView listView = findViewById(R.id.app_lv); AppNameList = Arrays. AsList (" QQ ", "WeChat", "cow guest", "China merchants bank", "pay treasure"); //listView.setAdapter(new AppListAdapterBase()); listView.setAdapter(new AppListAdapter(getAppInfo())); Private List<ResolveInfo> getAppInfo(){Intent Intent = new Intent(intent.action_main, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); return getPackageManager().queryIntentActivities(intent, 0); } public class AppListAdapter extends BaseAdapter { private List<ResolveInfo> resolveInfoList; public AppListAdapter(List<ResolveInfo> appInfo) { this.resolveInfoList = appInfo; } @Override public int getCount() { return resolveInfoList.size(); } @Override public Object getItem(int position) { return resolveInfoList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = getLayoutInflater(); convertView = layoutInflater.inflate(R.layout.item_app_list, null); ImageView iv = convertView.findViewById(R.id.app_icon_iv); TextView tv = convertView.findViewById(R.id.app_name_tv); ResolveInfo resolveInfo = resolveInfoList.get(position); tv.setText(resolveInfo.activityInfo.loadLabel(getPackageManager())); iv.setImageDrawable(resolveInfo.activityInfo.loadIcon(getPackageManager())); / / here to each entry set convertView. Click event setOnClickListener ((v) - > {String packageName. = resolveInfo activityInfo. PackageName; String className = resolveInfo.activityInfo.name; ComponentName componentName = new ComponentName(packageName, className); Intent intent = new Intent(); intent.setComponent(componentName); startActivity(intent); }); return convertView; }} // The basic data display, Public class AppListAdapterBase extends BaseAdapter {@override public int getCount() {return appNameList.size(); } @Override public Object getItem(int position) { return appNameList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = getLayoutInflater(); convertView = layoutInflater.inflate(R.layout.item_app_list, null); ImageView iv = convertView.findViewById(R.id.app_icon_iv); TextView tv = convertView.findViewById(R.id.app_name_tv); tv.setText(appNameList.get(position)); return convertView; }}}Copy the code

Click events and long press events

public class AppListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); ListView listView = findViewById(R.id.app_lv); AppNameList = Arrays. AsList ("QQ", "wechat "," MOOC ", "Niuke "); List<ResolveInfo> resolveInfoList = getAppInfo(); listView.setAdapter(new AppListAdapter(resolveInfoList)); / / click event writing two listView. SetOnItemClickListener ((the parent, the view, the position, id) -> { ResolveInfo resolveInfo = resolveInfoList.get(position); String packageName = resolveInfo.activityInfo.packageName; String className = resolveInfo.activityInfo.name; ComponentName componentName = new ComponentName(packageName, className); Intent intent = new Intent(); intent.setComponent(componentName); startActivity(intent); }); / / long press event listView. SetOnItemLongClickListener ((the parent, the view, the position, id) -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); Builder. SetTitle (" tip "); Builder.setmessage (" Are you sure?" ); Builder. SetPositiveButton (" sure, "(dialog, which) - > {/ / move this entry resolveInfoList. Remove (position); listView.setAdapter(new AppListAdapter(resolveInfoList)); }); Builder. SetNegativeButton (" cancel ", null); builder.show(); return false; }); Private List<ResolveInfo> getAppInfo(){Intent Intent = new Intent(intent.action_main, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); return getPackageManager().queryIntentActivities(intent, 0); } public class AppListAdapter extends BaseAdapter { private List<ResolveInfo> resolveInfoList; public AppListAdapter(List<ResolveInfo> appInfo) { this.resolveInfoList = appInfo; } @Override public int getCount() { return resolveInfoList.size(); } @Override public Object getItem(int position) { return resolveInfoList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = getLayoutInflater(); convertView = layoutInflater.inflate(R.layout.item_app_list, null); ImageView iv = convertView.findViewById(R.id.app_icon_iv); TextView tv = convertView.findViewById(R.id.app_name_tv); ResolveInfo resolveInfo = resolveInfoList.get(position); tv.setText(resolveInfo.activityInfo.loadLabel(getPackageManager())); iv.setImageDrawable(resolveInfo.activityInfo.loadIcon(getPackageManager())); / / click event writing a convertView. SetOnClickListener ((v) - > {String packageName. = resolveInfo activityInfo. PackageName; String className = resolveInfo.activityInfo.name; ComponentName componentName = new ComponentName(packageName, className); Intent intent = new Intent(); intent.setComponent(componentName); startActivity(intent); }); return convertView; }}}Copy the code

Set HeaderView and FooterView header_app_list.xml

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:gravity="center" android:textSize="20sp" android:text="This is listView's header." android:id="@+id/header_app_list_iv" android:background="@color/colorAccent" android:layout_width="match_parent" android:layout_height="80dp"/> </LinearLayout>Copy the code

Applistactivity.java (just do addHeaderView before setAdapter)

public class AppListActivity extends AppCompatActivity { private List<String> appNameList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); ListView listView = findViewById(R.id.app_lv); AppNameList = Arrays. AsList (" QQ ", "WeChat", "mu class network", "cow guest", "China merchants bank"); Public view (public view) {public view (public view) {public view (public view) {public view (public view)}} List<ResolveInfo> resolveInfoList = getAppInfo(); listView.setAdapter(new AppListAdapter(resolveInfoList)); / / click event writing two listView. SetOnItemClickListener ((the parent, the view, the position, id) -> { ResolveInfo resolveInfo = resolveInfoList.get(position); String packageName = resolveInfo.activityInfo.packageName; String className = resolveInfo.activityInfo.name; ComponentName componentName = new ComponentName(packageName, className); Intent intent = new Intent(); intent.setComponent(componentName); startActivity(intent); }); / / long press event listView. SetOnItemLongClickListener ((the parent, the view, the position, id) -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); Builder. SetTitle (" tip "); Builder.setmessage (" Are you sure?" ); Builder. SetPositiveButton (" sure, "(dialog, which) - > {resolveInfoList. Remove (position); listView.setAdapter(new AppListAdapter(resolveInfoList)); }); Builder. SetNegativeButton (" cancel ", null); builder.show(); return false; }); Private List<ResolveInfo> getAppInfo(){Intent Intent = new Intent(intent.action_main, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); return getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL); } public class AppListAdapter extends BaseAdapter { private List<ResolveInfo> resolveInfoList; public AppListAdapter(List<ResolveInfo> appInfo) { this.resolveInfoList = appInfo; } @Override public int getCount() { return resolveInfoList.size(); } @Override public Object getItem(int position) { return resolveInfoList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = getLayoutInflater(); convertView = layoutInflater.inflate(R.layout.item_app_list, null); ImageView iv = convertView.findViewById(R.id.app_icon_iv); TextView tv = convertView.findViewById(R.id.app_name_tv); ResolveInfo resolveInfo = resolveInfoList.get(position); tv.setText(resolveInfo.activityInfo.loadLabel(getPackageManager())); iv.setImageDrawable(resolveInfo.activityInfo.loadIcon(getPackageManager())); return convertView; }}}Copy the code

ListView optimization in the true sense optimization: www.xuanyusong.com/archives/12…

public class AppListActivity extends AppCompatActivity { private List<String> appNameList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); ListView listView = findViewById(R.id.app_lv); AppNameList = Arrays. AsList (" QQ ", "WeChat", "mu class network", "cow guest", "China merchants bank", "pay treasure"); Public view (public view) {public view (public view) {public view (public view) {public view (public view)}} List<ResolveInfo> resolveInfoList = getAppInfo(); listView.setAdapter(new AppListAdapter(resolveInfoList)); Private List<ResolveInfo> getAppInfo(){Intent Intent = new Intent(intent.action_main, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); return getPackageManager().queryIntentActivities(intent, 0); } public class AppListAdapter extends BaseAdapter { private List<ResolveInfo> resolveInfoList; public AppListAdapter(List<ResolveInfo> appInfo) { this.resolveInfoList = appInfo; } @Override public int getCount() { return resolveInfoList.size(); } @Override public Object getItem(int position) { return resolveInfoList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView == null){ LayoutInflater layoutInflater = getLayoutInflater(); convertView = layoutInflater.inflate(R.layout.item_app_list, null); viewHolder = new ViewHolder(); viewHolder.imageView = convertView.findViewById(R.id.app_icon_iv); viewHolder.textView = convertView.findViewById(R.id.app_name_tv); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } ResolveInfo resolveInfo = resolveInfoList.get(position); viewHolder.textView.setText(resolveInfo.activityInfo.loadLabel(getPackageManager())); viewHolder.imageView.setImageDrawable(resolveInfo.activityInfo.loadIcon(getPackageManager())); return convertView; } } // ViewHolder private static class ViewHolder { public ImageView imageView; public TextView textView; }}Copy the code

Item layout categories load item_left_chat.xml

<? The XML version = "1.0" encoding = "utf-8"? > <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/time_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="21:52" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" tools:ignore="MissingConstraints" /> <ImageView android:id="@+id/icon_iv" android:src="@mipmap/ic_launcher" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@+id/time_tv" tools:ignore="MissingConstraints" /> <TextView android:id="@+id/name_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tim" app:layout_constraintEnd_toEndOf="@+id/icon_iv" app:layout_constraintStart_toStartOf="@+id/icon_iv" app:layout_constraintTop_toBottomOf="@+id/icon_iv" /> <TextView android:id="@+id/content_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, how are you?" android:paddingStart="10sp" app:layout_constraintBottom_toBottomOf="@+id/icon_iv" app:layout_constraintStart_toEndOf="@+id/icon_iv" app:layout_constraintTop_toTopOf="@+id/icon_iv" tools:ignore="MissingConstraints" /> </androidx.constraintlayout.widget.ConstraintLayout>Copy the code

item_right_chat.xml

<? The XML version = "1.0" encoding = "utf-8"? > <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/time_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="21:52" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" tools:ignore="MissingConstraints" /> <TextView android:id="@+id/name_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tim" app:layout_constraintEnd_toEndOf="@+id/icon_iv" app:layout_constraintStart_toStartOf="@+id/icon_iv" app:layout_constraintTop_toBottomOf="@+id/icon_iv" /> <TextView android:id="@+id/content_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, how are you?" android:paddingEnd="10sp" app:layout_constraintBottom_toBottomOf="@+id/icon_iv" app:layout_constraintEnd_toStartOf="@+id/icon_iv" app:layout_constraintTop_toTopOf="@+id/icon_iv" tools:ignore="MissingConstraints" /> <ImageView android:id="@+id/icon_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/time_tv" tools:ignore="MissingConstraints" /> </androidx.constraintlayout.widget.ConstraintLayout>Copy the code

We now have item_left_chat. XML and item_right_chat. XML layouts, so all we need to do is load the categorized layout:

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.main_lv); List<ChatMessage> chatMessages = Arrays.asList( new ChatMessage(1, 2, "Tim", "08:20", "I'm Tim.", true), new ChatMessage(1, 2, "Tim", "08:25", "Jone, how are you?" , true), new ChatMessage(2, 1, "Jone", "08:30", "I'm fine, thinks", false), new ChatMessage(1, 2, "Tim", "08:31", "No thinks.", true), new ChatMessage(2, 1, "Jone", "08:32", "What can I do for you ?" , false), new ChatMessage(1, 2, "Tim", "08:59", "Please give me some money.", true) ); listView.setAdapter(new ChatMessageAdapter(chatMessages, MainActivity.this)); } static class ChatMessage { public int mId; public int mFriendId; public String mName; public String mDate; public String mContent; public boolean mIsComeMessage; public ChatMessage(int mId, int mFriendId, String mName, String mDate, String mContent, boolean mIsComeMessage) { this.mId = mId; this.mFriendId = mFriendId; this.mName = mName; this.mDate = mDate; this.mContent = mContent; this.mIsComeMessage = mIsComeMessage; } } static class ChatMessageAdapter extends BaseAdapter { List<ChatMessage> chatMessages; Context context; interface IMessageViewType { int COM_MESSAGE = 1; int TO_MESSAGE = 2; } public ChatMessageAdapter(List<ChatMessage> chatMessages, Context context) { this.chatMessages = chatMessages; this.context = context; } @Override public int getCount() { return chatMessages.size(); } @Override public Object getItem(int position) { return chatMessages.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); ChatMessage chatMessage = chatMessages.get(position); if(convertView == null){ if(chatMessage.mIsComeMessage){ convertView = layoutInflater.inflate(R.layout.item_left_chat, null); }else{ convertView = layoutInflater.inflate(R.layout.item_right_chat, null); } TextView timeTv = convertView.findViewById(R.id.time_tv); ImageView iconIv = convertView.findViewById(R.id.icon_iv); TextView nameTv = convertView.findViewById(R.id.name_tv); TextView contentTv = convertView.findViewById(R.id.content_tv); timeTv.setText(chatMessage.mDate); nameTv.setText(chatMessage.mName); contentTv.setText(chatMessage.mContent); } return convertView; } @Override public int getItemViewType(int position) { ChatMessage chatMessage = chatMessages.get(position); return chatMessage.mIsComeMessage ? IMessageViewType.COM_MESSAGE : IMessageViewType.TO_MESSAGE; } @Override public int getViewTypeCount() { return 2; // IMessageViewType;Copy the code

CardView

CardView is an important control for implementing a card-like layout effect. It’s actually a FrameLayout, but with rounded corners and shadows, it looks stereo.

What is CardView?

Android5.0 after new com. Android. Support: cardview – v7:26.1.0 independent introduced inherited from FrameLayout, convenient as other controls container, add 3 d shadow and rounded edge

Common properties of CardView

CardBackgroundColor sets the background color cardCornerRadius sets the radius of the corner contentPadding sets the inner padding cardElevation sets the shadow size cardUseCompatPadding CardPreventCornerOverlap Default is true for under 5.0, add extra padding to prevent content and rounded corners from overlapping

Common properties of CardView

Introduce a dependency for CardView

Implementation 'androidx. Cardview: cardview: 1.0.0'

A small Demo of VardView:

<? The XML version = "1.0" encoding = "utf-8"? > <FrameLayout 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" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity"> <! CardBackgroundColor: Sets the background color cardCornerRadius: sets the rounded corner cardElevation: sets the shadow contentPadding: Set up internal padding - > < androidx. Cardview. Widget. The cardview android: layout_gravity = "center" app:cardBackgroundColor="@color/colorAccent" app:cardCornerRadius="10dp" app:cardElevation="5dp" app:contentPadding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_width="200dp" android:layout_height="50dp" android:text="Hello World!" android:gravity="center" android:layout_gravity="center" /> </androidx.cardview.widget.CardView> </FrameLayout>Copy the code

And you can actually see that the CardView actually has a card effect. Common attributes are as follows:

Card_view :cardElevation Shadow size card_view:cardMaxElevation Maximum shadow height card_view:cardBackgroundColor Background color of the card Card_view: cardCornerRadius card the size of the fillet card_view: contentPadding card content in the margin of interval card_view: contentPaddingBottom CARDS at the bottom of the content and margin Card_view :contentPaddingTop The margin between the content of the card and the top Card_view: contentPaddingStart card content in the margin of interval starting card_view: contentPaddingEnd card content in the margin of interval terminates card_view: cardUseCompatPadding Sets the padding, V21 + version and previous version is still the same calculation card_view: cardPreventCornerOverlap in V20 adding padding and the previous version, this attribute in order to prevent the content and the bottom of the overlap

CardView example

Img01-img05 (drawable, xxhdPI)

Item_msg. XML, which is the layout of the ListView items:

<? The XML version = "1.0" encoding = "utf-8"? > <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"> <androidx.cardview.widget.CardView app:cardCornerRadius="8dp" app:cardElevation="5dp" app:cardUseCompatPadding="false" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/item_icon_iv" android:scaleType="centerCrop" tools:src="@drawable/img01" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/item_title_tv" android:layout_margin="8dp" Android :textColor="#000000" Android :textSize="16sp" Android :textStyle="bold" Tools :text=" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/item_content_tv" android:layout_margin="8dp" android:textColor="#000000" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" Android :layout_marginBottom="8dp" Tools :text=" learn Android, learn Android" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> </androidx.cardview.widget.CardView> </FrameLayout>Copy the code

main_activity.xml

<? The XML version = "1.0" encoding = "utf-8"? > <ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/id_listview_msg_list" android:divider="@null" android:background="#ffffff" android:paddingTop="8dp" tools:context=".MainActivity"> </ListView>Copy the code

MainActivity.java

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Enclosing setTitle (" CardView test "); setContentView(R.layout.activity_main); ListView msgListView = findViewById(R.id.id_listview_msg_list); List<Msg> messageList = Arrays. AsList (new Msg(1, r.rawable. Img01, "How to not miss the age of artificial intelligence?" "The next era is machine learning, seeing the future with you!" Img02), new Msg(2, r.rawable. Img02, "About your interview and Internship experience "," Rich prizes and participation awards, random draw 5 lucky users, get any paid interview course!" ), new Msg(3, r.rawable. Img03, "Dog food is not something you can just eat!" ", "Have you started your circle of friends? Half love, half sentimental! Not afraid, accompany you to go on strongly!" ), new Msg(4, r.rawable. Img04, "Front-end job interview things ~"," I have worked for a few years, the project is too simple to handle what to do? I haven't graduated yet. I'm learning front end by myself. Can I find a front end job? ), new Msg(5, r.drawable. Img05, "Illustration how programmers spend Qixi Festival?" ", "Graphic programmers how to spend Tanabata, ha ha ha, deserve to be single for 25 years!" )); msgListView.setAdapter(new MoocAdapter(messageList)); } class MoocAdapter extends BaseAdapter { private List<Msg> msgList; public MoocAdapter(List<Msg> msgList) { this.msgList = msgList; } @Override public int getCount() { return msgList.size(); } @Override public Object getItem(int position) { return msgList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView == null){ convertView = View.inflate(MainActivity.this, R.layout.item_msg, null); //convertView = getLayoutInflater().inflate(R.layout.item_msg, null); viewHolder = new ViewHolder(); viewHolder.iconImageView = convertView.findViewById(R.id.item_icon_iv); viewHolder.titleTextView = convertView.findViewById(R.id.item_title_tv); viewHolder.contentTextView = convertView.findViewById(R.id.item_content_tv); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } Msg msg = msgList.get(position); viewHolder.contentTextView.setText(msg.getContent()); viewHolder.titleTextView.setText(msg.getTitle()); viewHolder.iconImageView.setImageResource(msg.getImgResId()); return convertView; } } static class ViewHolder { ImageView iconImageView; TextView titleTextView; TextView contentTextView; } } @Data @AllArgsConstructor @NoArgsConstructor class Msg { private int id; private int imgResId; private String title; private String content; }Copy the code

Take a look at the final presentation:

As lombok is used here, let’s take a look at how lombok is used in Android development.

Preview using tools

<! - the introduction of the tools command space - > XMLNS: tools = "http://schemas.android.com/tools" < TextView android: id = "@ + id/item_title_tv" android:layout_margin="8dp" android:textColor="#000000" android:textSize="16sp" android:textStyle="bold" Android :layout_width="match_parent" Android :layout_height="wrap_content"/>Copy the code

You can use tools to preview the effect of the control. If you write android:text=XXX, it is likely that the android:text property will display if the data is not loaded correctly. So you can use the Tools namespace whenever you need to add data to an ImageView or a TextView to preview it.

Lombok in Android

Introducing Lombok’s dependencies:

/ / this is depend on the implementation of CardView 'androidx. CardView: CardView: 1.0.0' / / configuration Lombok annotation processor annotationProcessor group: Org. projectLombok ', name: 'lombok', version: '1.18.12' // Declare Lombok's dependency compileOnly(group: 'org. projectLombok ', name: 'lombok, version:' 1.18.12 ')Copy the code

Install Lombok plug-ins:

After installing the plug-in, restart AndroidStudio to use the Lombok plug-in.

Finally, don’t forget to create a new Lombok.config under moudle or Project:

Lombok. AnyConstructor. SuppressConstructorProperties = true and then start to write code ~ happy

Compile-time coding error solution

android {
    compileSdkVersion ...
    buildToolsVersion "..."
    
    // 指定编码为UTF-8
    compileOptions {
        encoding "UTF-8"
    }
    ...
}
Copy the code