Adapter mode of Android development series

There are two filling modes for data sources in Android development:
For fixed data: such as string-array in strings.xml, use android: entries to fill;
for dynamic data: Java array or database, use adapter to fill.

Adapter design pattern:
Usually there are many methods in the interface, and the program does not necessarily use all the methods, but all methods must be rewritten when implementing the interface using implements; the adapter is a class, which simplifies the above operations and implements the listener interface. All methods are written, but all methods are empty. The adapter needs to be defined as an abstract class, because it does not make sense to use it to create an object and call an empty method. The advantage is that it has good reusability/flexibility/extensibility and conforms to the principle of opening and closing (expanding open, modifying and closing).

Two ways of writing the adapter are (basic adapter):

//第一种写法:
//Drink为定义的饮料类,Drink.drinks为实现的Drink类对象数组
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,Drink.drinks);
//找到布局中的ListView
ListView listDrinks = findViewById(R.id.list_drinks);
//填充适配器
listDrinks.setAdapter(listAdapter);

//第二种写法:利用匿名内部类实现
((ListView)findViewById(R.id.list_drinks)).setAdapter(
                new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,Drink.drinks)
);

Supplement anonymous inner class: it
is a simplified way of writing inner class, provided that there is a class or interface, the class here can be a concrete class or an abstract class.
Format: new class name or interface name () {override method;}
essence: it is an anonymous object of a subclass that inherits this class or implements this interface.
Anonymous inner classes are often passed as parameters in development: such as:

public static void main(String[] args){
    
    
	Demo d = new Demo();
	d.method(new c(){
    
    
		public void show(){
    
    
			System.out.println("AAA");
		}
	});
}

Inner class (class defined in the class):
Access features: the
inner class can directly access the members of the outer class, including private members; the
outer class must create an object to access the members of the inner class; the
name of the outer class. The name of the inner class object name = External class object. Internal class object
OI oi = new O().new I();

Reference materials:
https://www.icourse163.org/learn/BFU-1205989803?tid=1450759471&from=study#/learn/content MOOC course on mobile development technology

Guess you like

Origin blog.csdn.net/langxiaolin/article/details/113881243