First, UI basic introduction
1. LinerLayout
Important attributes
Android: Orientation: Verticle /horhorizontal: Vertical/horizontalandroid:layout_weight Android: layout_gravity GravityCopy the code
2. RelativeLayout
android:layout_centerInParent
android:layout_alignParentLeft
android:layout_alignParentRight
android:layout_alignParentTop
android:layout_alignParentBottom
android:layout_centerHorizontal
android:layout_centerVertical
1.On some side of the referenceandroid:layout_toLeftOf
android:layout_toRightOf
android:layout_above
android:layout_below
2.Align with one of the edges of the referenceandroid:layout_alignTop
android:layout_alignBottom
android:layout_alignLeft
android:layout_alignRight
Copy the code
3. FrameLayout
android:layout_gravity="center"The force of gravityandroid:foreground="@mipmap/ic_launcher"prospectsandroid:foregroundGravity="right|bottom"Prospects of gravityCopy the code
4. TableLayout
If we want to have multiple controls on the same row, we wrap a pair of TableRow around those controls and in this case, the control widths match the contentandroid:stretchColumns="*"Set columns that can be stretched, directly pass the index of the column, if there are more than one column, with, as the partition, * represents allandroid:shrinkColumns Sets columns that can be shrunkandroid:collapseColumns="1"Sets the columns that can be hiddenCopy the code
5. GridLayout
Android: rowCount android: columnCount Android: layout_row Android: layout_rowSpan android: layout_rowSpanCopy the code
6. ConstraintLayout
App :layout_constraint position _to position Of="?"
? : 1. parent 2.Reference other control ID An orientation of the current control is aligned with an orientation of another referenceapp:layout_constraintLeft_toLeftOf corresponds to the alignLeft attribute of RelativeLayoutapp:layout_constraintRight_toRightOf corresponds to the alignRight property of RelativeLayoutapp:layout_constraintTop_toTopOf corresponds to the alignTop property of RelativeLayoutapp:layout_constraintBottom_toBottomOf corresponds to the alignBottom property of a RelativeLayoutapp:layout_constraintStart_toStartOf 同Left_toLeftOf
app:layout_constraintEnd_toEndOf the same as Right_toRightOf The A side of the current control will be on the B side of the referenceapp:layout_constraintLeft_toRightOf corresponds to the toRightOf RelativeLayoutapp:layout_constraintRight_toLeftOf corresponds to the toLeftOf of RelativeLayoutapp:layout_constraintTop_toBottomOf corresponds to below with a RelativeLayoutapp:layout_constraintBottom_toTopOf corresponds to above the RelativeLayoutapp:layout_constraintStart_toEndOf 同Left_toRightOf
app:layout_constraintEnd_toStartOf 同Right_toLeftOf
app:layout_constraintVertical_bias="0.53"Vertical offset,0.5In the middleapp:layout_constraintHorizontal_bias="0.53"Horizontal offset,0.5In the middleCopy the code
7.UI basic controls
View
View that handles text content (TextView)
1. Inheritance relationship of TextView
- Display processing for long text - support FOR HTML code - style content, link effectCopy the code
2. Clicked View (Button)
Button registers methods for clicking events
1. Customize inner classes
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Implementing click events through custom inner classes"/>
Copy the code
//1. Get the button
Button btn1 = findViewById(R.id.btn1);
// Click event: the event that is triggered when clicked
MyClickListener mcl = new MyClickListener();
//2. Register the click event listener for the button
btn1.setOnClickListener(mcl);
Copy the code
class MyClickListener implements View.OnClickListener{
@Override
public void onClick(View view) {
// Print a statement on the console
Log.e("TAG"."The button that registered the inner class listener object when the button was just clicked."); }}Copy the code
2. Anonymous inner classes
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click events via anonymous inner classes"/>
Copy the code
// Anonymous inner classes apply to buttons that have unique actions
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Output at the console
Log.e("TAG"."========== Anonymous inner class =========="); }});Copy the code
3. The current Activity implements the event interface
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Implement the click event interface through the current Activity"/>
Copy the code
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(this);
@Override
public void onClick(View view) {
Log.e("TAG"."Implement OnClickListener with this class");
}
Copy the code
4. Add click event properties to the current layout file
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind in an XML file"
android:onClick="myClick"/>
<Button
android:id="@+id/btn5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind 2 in an XML file"
android:onClick="myClick"/>
Copy the code
// Parameter: the control object to be clicked
public void myClick(View v){
switch (v.getId()){
case R.id.btn4:
Log.e("TAG"."btn4======");
break;
case R.id.btn5:
Log.e("TAG"."btn5======");
break; }}Copy the code
3. Handle image content View (ImageView)
A control used to display and control an image, which can be zoomed in, zoomed out, rotated, etc. Common attributes are:
android:src
android:background
Copy the code
4. View (EditText) that receives user input
android:inputType
android:hint
android:maxLength
Copy the code
5. View (ProgressBar)
The progress bar, which by default is round and has no scale, is a constantly rotating animation. By setting the style, you can display the traditional horizontal graduated progress bar.
<! Progress bar: The default style is circle. Modify the style needs to set style style set style progressBarStyleHorizontal (horizontal bar)android:progress=""Set up the scheduleandroid:max=""Set maximum value, default100
android:indeterminate="true"Set the progress bar to keep scrolling --><ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="? android:attr/progressBarStyleHorizontal"
android:progress="30"
android:max="200"/>
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="? android:attr/progressBarStyleHorizontal"
android:indeterminate="true"/>
<ProgressBar
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="? android:attr/progressBarStyleHorizontal"/>
Copy the code
final ProgressBar progressBar = findViewById(R.id.progress);
progressBar.setProgress(80);
// In Android, after 4.0, controls cannot be manipulated directly in a thread
// Progress bar is a special case
new Thread(){
@Override
public void run() {
for(int i = 1 ; i <= 100 ; i++) {
progressBar.setProgress(i);
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
Copy the code
General properties
2. Common UI components
1. Introduction to the Activity
1. Jump between activities
<TextView
android:id="@+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"/>
Copy the code
// Use findViewById to find the layout control and convert it to View
final TextView textView = findViewById(R.id.titleTextView);
// Hit button view
Button button = findViewById(R.id.button);
// Set the click event
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Dynamically sets the text for the textView
textView.setText(getString(R.string.app_name));
// Jump to a NewActivity
Intent intent = newIntent(TestActivity.this, TestActivity.class); startActivity(intent); }});Copy the code
2.Activity Four startup modes
// Set launchMode: Android :launchMode="singleTop"
<activity android:name=".TestActivity"
android:launchMode="singleTop"
android:label="testActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Copy the code
1.standard
2.singleTop
3.singleTask
4.singleInstance
2. Create and use Android menus
1. Menu categories
1. OptionMenu
The Options menu is the main item of an application and is used to place actions that have a global impact on the application, such as search/Settings.
1. Design menu through XML resources
<? xml version="1.0" encoding="utf-8"? ><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<! --showAsAction Property values: always: display directly in the title bar never: never display withText: control icon and text display together ifRoom: display when there is space -->
<item android:title="Save"
android:id="@+id/save"
android:icon="@mipmap/ic_launcher"
app:showAsAction="always"/>
<item android:title="Settings"
android:id="@+id/setting"/>
<item android:title="More operations" >
<menu >
<item android:title="Quit"
android:id="@+id/exit"/>
<item android:title="Submenu 2" />
<item android:title="Submenu 3" />
</menu>
</item>
</menu>
Copy the code
public boolean onCreateOptionsMenu(Menu menu) {
// Load menu resources
// Design menu from XML resources
getMenuInflater().inflate(R.menu.option,menu);
// Remember to return true, otherwise the menu will not be displayed
return true;
}
Copy the code
2. Pure Java code design menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Pure Java code design menu
/* Set more add/remove */
// Menu
// Parameter 1: group ID Parameter 2: menu item ID Parameter 3: serial number parameter 4: Settings
menu.add(1.1.1."Settings");
SubMenu sub = menu.addSubMenu(1.2.2."More");
// SubMenu
sub.add(2.3.1."Add");
sub.add(2.4.2."Delete");
// Remember to return true, otherwise the menu will not be displayed
return true;
}
Copy the code
//OptionMenu Selects the menu item
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case 1:
Toast.makeText(this."Settings",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this."More",Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this."Add",Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this."Delete",Toast.LENGTH_SHORT).show();
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
Copy the code
2. ContextMenu
Holding on to an item will bring up the ContextMenu in the middle of the screen.
<? xml version="1.0" encoding="utf-8"? ><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/delete"
android:title="Delete" />
<item android:title="Rename" >
<menu >
<item
android:id="@+id/opera1"
android:title=Following the "1" />
<item
android:id="@+id/opera2"
android:title="Operating 2" />
</menu>
</item>
</menu>
Copy the code
// ctx_bTN: demonstrates ContextMenu
/ / 1. Registration
registerForContextMenu(findViewById(R.id.ctx_btn));
//2. Create override onCreateContextMenu
//3. The menu item operation overwrites onContextItemSelected
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.delete:
Toast.makeText(this."Delete",Toast.LENGTH_SHORT).show();
break;
case R.id.opera1:
Toast.makeText(this.Following the "1",Toast.LENGTH_SHORT).show();
break;
case R.id.opera2:
Toast.makeText(this."Operating 2",Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
Copy the code
If you want to set the context operation mode for the button:
// Implement ActionMode CallBack
// Start the context mode in the view long press event
findViewById(R.id.ctx_btn).setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
startActionMode(cb);
return false; }}); ActionMode.Callback cb =new ActionMode.Callback() {
// Created when the context operation mode (startActionMode(Callback)) is started
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
Log.e("TAG"."Create");
getMenuInflater().inflate(R.menu.context,menu);
return true;
}
// call after the method is created
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
Log.e("TAG"."Ready");
return false;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
Log.e("TAG"."Click");
switch (menuItem.getItemId()){
case R.id.delete:
Toast.makeText(MainActivity.this,"Delete",Toast.LENGTH_SHORT).show();
break;
case R.id.opera1:
Toast.makeText(MainActivity.this,Following the "1",Toast.LENGTH_SHORT).show();
break;
case R.id.opera2:
Toast.makeText(MainActivity.this,"Operating 2",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
// Called when the context operation mode ends
@Override
public void onDestroyActionMode(ActionMode actionMode) {
Log.e("TAG"."The end"); }};Copy the code
3. PopupMenu
A pop-up style menu displayed in modal form, tied to a View, with a version appearing below the bound View.
<? xml version="1.0" encoding="utf-8"? ><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/copy"
android:title="Copy" />
<item
android:id="@+id/paste"
android:title="Paste" />
</menu>
Copy the code
/ / popup_btn: demo PopupMenu
final Button popupBtn = findViewById(R.id.popup_btn);
popupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// instantiate PopupMenu object (parameter 2: anchored view)
final PopupMenu menu = new PopupMenu(MainActivity.this,popupBtn);
//② Load Menu resources: Use MenuInflater to load Menu resources into the Menu object returned by popupmenu.getmenu ()
// Load the menu resources for r.menu. xx into the pop-up menu
menu.getMenuInflater().inflate(R.menu.popup,menu.getMenu());
//③ Set the click listener for PopupMenu
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.copy:
Toast.makeText(MainActivity.this,"Copy",Toast.LENGTH_SHORT).show();
break;
case R.id.paste:
Toast.makeText(MainActivity.this,"Paste",Toast.LENGTH_SHORT).show();
break;
}
return false; }});// Do not forget this step, display PopupMenumenu.show(); }});Copy the code
2. Advantages of XML definition Menu
- Clear menu structure
- Separate menu content from application logic code
- Resource fit is easier
3. Menu defined by XML is not displayed
- OnCreateOptionsMenu () must return true
- The onOptionsItemSelected method returns true
- Invoke the default implementation of the parent class
3.Android dialog box processing
1.AlertDialog
2. Customize Dialog
3.PopupWindow
4.Activity lifecycle
1.Activity lifecycle
public class MainActivity extends AppCompatActivity {
// Lifecycle of a single Activity:
OnCreate -->onStart-->onReusme --> onPause-->onStop-->onDestory
// Start onCreate-->onStart-->onResume
//2. If the Activity is already in the foreground, click the home button to leave the current Activity, OnPause-->onStop,
/ / back to the Activity: onRestart -- - > onStart -- - > onResume
//3. The Activity cannot be used onPause-->onStop, and the application is forcibly killed.
// Return to the Activity, onCreate-->onStart-->onResume
// Switch between multiple activities
// When another Activity is started, the current Activity: onPause-->onStop, when the back button is clicked,
// Make another Activity exit when the current Activity: onRestart-->onStart-->onResume
// The dialog box exists
//1. Normal dialogs have no impact on the lifecycle
//2. If an Activity masquerades as dialog mode, the Activity: onPause precedes it when it starts
// After the "dialog" disappears, the callback onResume returns to the foreground again
/ / create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("TAG"."OnCreate - create");
}
/ / start
@Override
protected void onStart() {
super.onStart();
Log.e("TAG"."OnStart -- start");
}
/ / recovery
@Override
protected void onResume() {
super.onResume();
Log.e("TAG"."OnResume -- back");
}
/ / pause
@Override
protected void onPause() {
super.onPause();
Log.e("TAG"."OnPause -- suspended");
}
/ / stop
@Override
protected void onStop() {
super.onStop();
Log.e("TAG"."onStop----停止");
}
/ / destroy
@Override
protected void onDestroy() {
super.onDestroy();
Log.e("TAG"."OnDestroy -- destroyed");
}
/ / restart
@Override
protected void onRestart() {
super.onRestart();
Log.e("TAG"."OnRestart -- to restart"); }}Copy the code
2. Start the Activity
1. Perform explicit startup
<Button
android:id="@+id/btn1"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Explicitly open the second screen"/>
Copy the code
public void myclick(View view){
switch (view.getId()){
case R.id.btn1:// Activate the second Ativity
/ / intention
// Parameter 1: context, current context (this).
// Parameter 2: the class object of the Activity to be jumped
Intent it = new Intent(this, Main2Activity.class);
startActivity(it);/ / start the Activity
break; }}Copy the code
2. Implicit startup
1. Implicitly start the system Activity(open a browser)
<Button
android:id="@+id/btn2"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Implicitly start system Activity(open browser)"/>
Copy the code
public void myclick(View view){
switch (view.getId()){
case R.id.btn2:// Implicitly start the system Activity
// Parameter 1: string (alias for an Activity)
// Parameter 2: the path to open, using the protocol to specify which Activity to open
Intent it2 = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")); //tel:13338889999
startActivity(it2);
break; }}Copy the code
2. Implicitly start normal activities
<Button
android:id="@+id/btn3"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Implicitly start normal activities" />
Copy the code
public void myclick(View view){
switch (view.getId()){
// Implicitly start normal activities
// ABC is an alias that needs to be added in the androidmanifest.xml file
case R.id.btn3:
Intent it3 = new Intent("abc");
startActivity(it3);
break;
}
Copy the code
<activity android:name=".Main2Activity">
<intent-filter>
<! -- alias -->
<action android:name="abc"/>
<! Grouping -- - >
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Copy the code
3.startActivityForResult
<Button
android:id="@+id/btn4"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start the Activity with a result return" />
Copy the code
public void myclick(View view){
switch (view.getId()){
case R.id.btn4:
Intent it4 = new Intent(this,Main2Activity.class);
// Parameter: request code
startActivityForResult(it4,1000);
break; }}Copy the code
// If the second Activity is started with startActivityForResult
OnActivityResult is automatically called when you return to the current Activity after the second Activity has finished processing
// In this method we can process the results returned by the second Activity (e.g., photos taken, images selected from the gallery).
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//resultCode: 0, RESULT_CANCEL cancel -1, RESULT_OK is returned after correct processing
if(resultCode == RESULT_OK) {
//requestCode: Specifies which Activity the result is from
if (requestCode == 1000) {
Log.e("TAG"."OnActivityResult automatically entered, requestCode=" + requestCode + ",resultCode=" + resultCode);
Log.e("TAG"."The data returned is:" + data.getStringExtra("myMsg")); }}}Copy the code
TextView txt = findViewById(R.id.txt);
txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent it = new Intent(); // It is intended not to be used as a jump interface, but to pass data
it.putExtra("myMsg"."Here's the information from the second interface.");
// Set the result
// parameter 1: resultCode, obtained from the onActivityResult method of the previous interface using resultCode
// Parameter 2: the intent object, which is used to put data in the onActivityResult method of the previous interfacesetResult(RESULT_OK, it); finish(); }});Copy the code
3.Activity information transfer
1. Pass common data
<Button
android:id="@+id/btn5"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Explicitly open the second screen and pass the data."/>
Copy the code
public void myclick(View view){
switch (view.getId()){
case R.id.btn5:// Activate the second Ativity
/ / intention
// Parameter 1: context, current context (this).
// Parameter 2: the class object of the Activity to be jumped
Intent it5 = new Intent(this,Main2Activity.class);
it5.putExtra("msg1".This is number one.);
it5.putExtra("msg2".100);
break; }}Copy the code
// If you want to retrieve the data from the previous interface, you first need to retrieve the intent to do the startup
Intent it = getIntent();
String msg1 = it.getStringExtra("msg1");
// Parameter 1: data name, parameter 2: default value
int msg2 = it.getIntExtra("msg2".0);
TextView txt = findViewById(R.id.txt);
txt.setText(msg1+""+msg2);
Copy the code
2. Pass object data
<Button
android:id="@+id/btn6"
android:onClick="myclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Explicitly open the second screen and pass the data."/>
Copy the code
// serialize:
//1. When you want to save an object in memory to a file or database
//2. Like using a Socket to pass objects across the network
public class Student implements Serializable {
private String name;
private int age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender; }}Copy the code
public void myclick(View view){
switch (view.getId()){
case R.id.btn6:// Activate the second Ativity
/ / intention
// Parameter 1: context, current context (this).
// Parameter 2: the class object of the Activity to be jumped
Intent it6 = new Intent(this,Main2Activity.class);
// Pass an object with an Intent
Student s = new Student("Zhang".22."Male");
it6.putExtra("stu",s);
break; }}Copy the code
// If you want to retrieve the data from the previous interface, you first need to retrieve the intent to do the startup
Intent it = getIntent();
// Get the serialized object
Student stu = (Student) it.getSerializableExtra("stu");
if(stu ! =null) {
TextView txt = findViewById(R.id.txt);
txt.setText(stu.getName() + "" + stu.getAge() + "" + stu.getGender());
}
Copy the code
5.Fragment Creation and use
1.Fragment sets thoughts
Why Fragment is needed
2.Fragment VS Activity
- Fragment is after Android3.0+
- An Activity can run multiple fragments
- Fragments cannot exist without an Activity
- An Activity is the body of the screen, and a Fragment is a component of an Activity
Fragment life cycle
public class Fragment1 extends Fragment {
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.e("TAG"."OnAttach --Fragment associated with Activity");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAG"."OnCreate --Fragment created");
}
//Fragment Creates a view
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("TAG"."OnCreateView --Fragment view created.");
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("TAG"."OnActivityCreated --Activity is already created");
}
@Override
public void onStart() {
super.onStart();
Log.e("TAG"."OnStart -- fragments start");
}
@Override
public void onResume() {
super.onResume();
Log.e("TAG"."OnResume -- fragments showed");
}
@Override
public void onPause() {
super.onPause();
Log.e("TAG"."OnPause -- fragments suspended");
}
@Override
public void onStop() {
super.onStop();
Log.e("TAG"."OnStop -- fragments to stop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.e("TAG"."OnDestroyView --Fragment view destruction");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG"."OnDestroy -- fragments destroyed");
}
@Override
public void onDetach() {
super.onDetach();
Log.e("TAG"."OnDetach -- Disassociate Activity"); }}Copy the code
4. Load the fragments
Static loading: XML
// Static loading: Specify the Fragment path using the Android :name attribute
// A Fragment named Fragment1 needs to be created
<fragment
android:id="@+id/fragment1"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:name="com.example.fragmentdemo.Fragment1"/>
Copy the code
2. Dynamic loading
<FrameLayout
android:id="@+id/container"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fragment1"></FrameLayout>
Copy the code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FragmentManager FragmentTransaction
Obtain the Fragment manager
FragmentManager manager = getSupportFragmentManager();
//2. Obtain the Fragment transaction (/ open the Fragment transaction)
FragmentTransaction transaction = manager.beginTransaction();
//3. Dynamically add Fragment
// Parameter 1: container ID
// Parameter 2: Fragment object
final Fragment f2 = new Fragment2(); // A Fragment named Fragment2 needs to be created
transaction.add(R.id.container,f2);
//4. Commit transaction
transaction.commit();
}
Copy the code
5. Fragments spread value
Consider the following example for passing values
activity_tab_fragment.xml
<? xml version="1.0" encoding="utf-8"? ><LinearLayout 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"
tools:context=".TabFragmentActivity"
android:orientation="vertical">
<! -- Loading Fragment container -->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="# 515151"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_index"
android:text="Home page"
android:drawableTop="@drawable/tab_menu_index"
style="@style/tab_menu_item"/>
<RadioButton
android:id="@+id/rb_channel"
android:text="Classification"
android:drawableTop="@drawable/tab_menu_channel"
style="@style/tab_menu_item"/>
<RadioButton
android:id="@+id/rb_list"
android:text="My Study"
android:drawableTop="@drawable/tab_menu_list"
style="@style/tab_menu_item"/>
<RadioButton
android:id="@+id/rb_me"
android:text="我"
android:drawableTop="@drawable/tab_menu_me"
style="@style/tab_menu_item"/>
</RadioGroup>
</LinearLayout>
Copy the code
tab_menu_bg.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape>
<solid android:color="#FFC4C4C4"></solid>
</shape>
</item>
<item>
<shape>
<solid android:color="@android:color/transparent"></solid>
</shape>
</item>
</selector>
Copy the code
tab_menu_channel.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/channel_selected" android:state_checked="true"></item>
<item android:drawable="@mipmap/channel_normal"></item>
</selector>
Copy the code
tab_menu_index.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/index_selected" android:state_checked="true"></item>
<item android:drawable="@mipmap/index_normal"></item>
</selector>
Copy the code
tab_menu_list.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/list_selected" android:state_checked="true"></item>
<item android:drawable="@mipmap/list_normal"></item>
</selector>
Copy the code
tab_menu_me.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/me_selected" android:state_checked="true"></item>
<item android:drawable="@mipmap/me_normal"></item>
</selector>
Copy the code
tab_menu_text.xml
<? xml version="1.0" encoding="utf-8"? ><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffffff" android:state_checked="true"/>
<item android:color="# 515151"/>
</selector>
Copy the code
TabFragmentActivity.java
package com.example.fragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class TabFragmentActivity extends AppCompatActivity implements Fragment3.MyListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_fragment);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, new IndexFragment());
transaction.commit();
}
public void myclick(View view){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch(view.getId()){
case R.id.rb_index:
transaction.replace(R.id.container, new IndexFragment());
break;
case R.id.rb_channel: // The Activity sends a value to the Fragment
//setArguments
//1. Instantiate Fragment
Fragment f1 = new Fragment1();
Instantiate a Bundle object
Bundle bundle = new Bundle();
//3. Store data into the Bundle object
bundle.putString("msg1"."This is the data that the Activity sends to the Fragment.");
//4. Call the Fragment setArguments method and pass in the Bundle object
f1.setArguments(bundle);
//5. Add or replace the displayed Fragment
transaction.replace(R.id.container, f1);
break;
case R.id.rb_list:
transaction.replace(R.id.container, new Fragment2());
break;
case R.id.rb_me:
transaction.replace(R.id.container, new Fragment3());
break;
}
transaction.commit();
}
@Override
public void sendMsg(String msg) {
Log.e("TAG"."Fragment returns data:"+msg); }}Copy the code
You need to create 4 fragments: Fragment1, Fragment2, Fragment3, and Fragment4
Fragment1 receive value
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_1, container, false);
Bundle bundle = getArguments();
String msg1 = bundle.getString("msg1");
((TextView)v.findViewById(R.id.txt1)).setText(msg1);
return v;
}
Copy the code
Fragment3 passes a value to the Activity
package com.example.fragment;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
//Fragment like Activity pass value (interface callback)
//1. Define an interface in which to declare a method for passing data
//2. Let the Activity implement the interface, then override the callback method, get the value passed in, and do the processing
//3. Declare a reference to the callback interface in a custom Fragment
//4. In the onAttach method, assign the reference to step 3
//5. Call the method passing the data in the reference
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_3, container, false);
}
private MyListener m1;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
m1 = (MyListener) getActivity();
m1.sendMsg("News");
}
public interface MyListener {
void sendMsg(Stringmsg); }}Copy the code
The Activity receives the value
@Override
public void sendMsg(String msg) {
Log.e("TAG"."Fragment returns data:" + msg);
}
Copy the code
6.ListView
1. The adapter
1.ArrayAdapter
//activity_array.xml<? 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"
tools:context=".ArrayActivity">
<ListView
android:id="@+id/list_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Copy the code
//ArrayActivity.java
//1. Prepare layout (display effect of each item)
//2. Prepare data sources
//3. Instantiate adapter (layout + data source)
//4. Set the adapter for ListView
public class ArrayActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_array);
ListView listView1 = findViewById(R.id.list_view1);
String[] data = {"AA"."BB"."CC"."DD"."EE"."FF"."GG"."AA"."BB"."CC"."DD"."EE"."FF"."GG"."AA"."BB"."CC"."DD"."EE"."FF"."GG"."AA"."BB"."CC"."DD"."EE"."FF"."GG"};
// Parameter 1: Context (this)
// Parameter 2: represents the layout applied to the data item
// Parameter 3: data source (array)
// 1.r.layout. item is a text-only layout written by itself
//ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item, data);
/ / 2. Android. R.l ayout. Simple_list_item_1 is the only android text layout
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, data);
//3. When the layout contains images and text, you can specify the text with the id
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item2, R.id.txt1, data); listView1.setAdapter(adapter); }}Copy the code
//item.xml<? xml version="1.0" encoding="utf-8"? ><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="28sp"
android:textColor="#ff0000"/>
Copy the code
//item2.xml<? 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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Copy the code
2.SimpleAdapter
//activity_simple.xml<? xml version="1.0" encoding="utf-8"? ><LinearLayout 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"
tools:context=".SimpleActivity">
<ListView
android:id="@+id/list_view2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Copy the code
//SimpleActivity.java
public class SimpleActivity extends AppCompatActivity {
private List<Map<String.Object>> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
//1. Get ListView object
ListView listView2 = findViewById(R.id.list_view2);
//2. Instantiate adapter objects
// Parameter 1: this
Parameter 2: data source
initData();
// Parameter 3: each layout item
// Parameter 4: Data source key array
String[] from = {"img"."name"."mood"};
// Parameter 5: array of ids where the data is going
int[] to = {R.id.qq_img, R.id.qq_name, R.id.qq_mood};
// The element of the from array on the index corresponds to the data source's map key, which is the data that the key replaces
// Will be displayed as the contents of the control represented by the id on the corresponding index of the TO array
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item3, from, to);
//3. Set the adapter for ListView
listView2.setAdapter(adapter);
//4. Click events
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView
adapterView, View view, int i, long l) {
// Use Toast to remind you of your Mood
Map<String.Object> map = data.get(i);
String name = map.get("name").toString();
String mood = map.get("mood").toString();
Toast.makeText(SimpleActivity.this, name+""+mood, Toast.LENGTH_SHORT).show(); }}); } privatevoid initData() {
// Left: profile picture right: name right: mood
Map<String.Object> map1 = new HashMap<>();
map1.put("img", R.mipmap.caocao);
map1.put("name"."Cao cao");
map1.put("mood"."Better to teach the world against me than the world against me.");
Map<String.Object> map2 = new HashMap<>();
map2.put("img",R.mipmap.zhenji);
map2.put("name"."Binjii");
map2.put("mood"."As if it were snow, as if it were light clouds covering the moon.");
Map<String.Object> map3 = new HashMap<>();
map3.put("img",R.mipmap.simayi);
map3.put("name".Sima Yi);
map3.put("mood"."The Child of Destiny.");
Map<String.Object> map4 = new HashMap<>();
map4.put("img",R.mipmap.guojia);
map4.put("name"."Country");
map4.put("mood"."Oh");
Map<String.Object> map5 = new HashMap<>();
map5.put("img",R.mipmap.caocao);
map5.put("name"."Cao cao");
map5.put("mood"."Better to teach the world against me than the world against me.");
Map<String.Object> map6 = new HashMap<>();
map6.put("img",R.mipmap.zhenji);
map6.put("name"."Binjii");
map6.put("mood"."As if it were snow, as if it were light clouds covering the moon.");
Map<String.Object> map7 = new HashMap<>();
map7.put("img",R.mipmap.simayi);
map7.put("name".Sima Yi);
map7.put("mood"."The Child of Destiny.");
Map<String.Object> map8 = new HashMap<>();
map8.put("img",R.mipmap.guojia);
map8.put("name"."Country");
map8.put("mood"."Oh"); data.add(map1); data.add(map2); data.add(map3); data.add(map4); data.add(map5); data.add(map6); data.add(map7); data.add(map8); }}Copy the code
//item3<? 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">
<ImageView
android:id="@+id/qq_img"
android:layout_width="50dp"
android:layout_height="65dp"
android:background="@mipmap/caocao"/>
<TextView
android:id="@+id/qq_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/qq_img"
android:textSize="26sp"
android:text="Cao cao"/>
<TextView
android:id="@+id/qq_mood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/qq_img"
android:layout_below="@id/qq_name"
android:textColor="#00ffff"
android:text="Test data"/>
</RelativeLayout>
Copy the code
3.BaseAdapter
//activity_base.xml<? xml version="1.0" encoding="utf-8"? ><FrameLayout 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"
tools:context=".BaseActivity">
<ListView
android:id="@+id/list_view3"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/write"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/write"
android:layout_gravity="right|bottom"
android:layout_margin="40dp"/>
</FrameLayout>
Copy the code
//BaseActivity.java
public class BaseActivity extends AppCompatActivity {
private ListView listView3;
private ImageView write;
private List<Msg> list = new ArrayList<>();
private int[] ps = {R.mipmap.profile1, R.mipmap.profile2, R.mipmap.profile3, R.mipmap.profile4, R.mipmap.profile5, R.mipmap.profile6, R.mipmap.profile7, R.mipmap.profile8};
private BaseAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
listView3 = findViewById(R.id.list_view3);
write = findViewById(R.id.write);
initData();
// Parameters to be passed: data source, environment
adapter = new MyAdapter(list, this);
// Set the adapter
listView3.setAdapter(adapter);
write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Msg m = new Msg(R.mipmap.profile9, "paradox"."This is a dynamic addition.".false);
list.add(m);
// Notify the adapter to update the data
adapter.notifyDataSetChanged();
// Set the listView to automatically display the latest datalistView3.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL); }}); } privatevoid initData() {
for (int i = 1; i <= 8 ; i++) {
Msg msg = new Msg(ps[i-1]."User"+i, "It's a fine day today, beautiful everywhere."+i, i%2= =0?true:false); list.add(msg); }}}Copy the code
//Msg.java
public class Msg {
private int profile;
private String nickname;
private String content;
private boolean isLike;
public int getProfile() {
return profile;
}
public void setProfile(int profile) {
this.profile = profile;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isLike() {
return isLike;
}
public void setLike(boolean like) {
isLike = like;
}
public Msg(int profile, String nickname, String content, boolean isLike) {
this.profile = profile;
this.nickname = nickname;
this.content = content;
this.isLike = isLike; }}Copy the code
//item4.xml<? 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">
<ImageView
android:id="@+id/profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/profile1"
android:layout_margin="5dp"/>
<TextView
android:id="@+id/nickname"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="User 1"
android:textSize="26sp"
android:layout_toRightOf="@id/profile"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="2048-10-24"
android:textSize="22sp"
android:layout_toRightOf="@id/profile"
android:layout_below="@id/nickname"/>
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Oh, what a meaningful day!!"
android:textSize="22sp"
android:layout_below="@id/profile"/>
<ImageView
android:id="@+id/repost"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/repost"
android:layout_below="@id/content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"/>
<ImageView
android:id="@+id/comment"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/comment"
android:layout_below="@id/content"
android:layout_toLeftOf="@id/repost"
android:layout_marginRight="10dp"/>
<ImageView
android:id="@+id/like"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/like"
android:layout_below="@id/content"
android:layout_toLeftOf="@id/comment"
android:layout_marginRight="10dp"/>
</RelativeLayout>
Copy the code
//MyAdapter.java
// Set the ListView effect one by one according to the prepared data source and subitem layout
// Do some details
public class MyAdapter extends BaseAdapter {
private List<Msg> list;
private Context ctx;
public MyAdapter(List<Msg> list, Context ctx) {
this.list = list;
this.ctx = ctx;
}
// Get the number (set the length of ListView)
@Override
public int getCount() {
return list.size();
}
// Get the view (sets the display effect of each item in the ListView) - executes as each view appears
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(ctx).inflate(R.layout.item4, null);
Msg msg = list.get(i);
/ / avatar
ImageView profile = view.findViewById(R.id.profile);
profile.setImageResource(msg.getProfile());
/ / nickname
TextView nickname = view.findViewById(R.id.nickname);
nickname.setText(msg.getNickname());
/ / content
TextView content = view.findViewById(R.id.content);
content.setText(msg.getContent());
// Whether to like
ImageView like = view.findViewById(R.id.like);
if(msg.isLike()){
like.setImageResource(R.mipmap.liked);
}else {
like.setImageResource(R.mipmap.like);
}
/ / comment
ImageView comment = view.findViewById(R.id.comment);
comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ctx, "You clicked on the comments.", Toast.LENGTH_SHORT).show(); }});/ / forwarding
ImageView repost = view.findViewById(R.id.repost);
repost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ctx, "You hit retweet.", Toast.LENGTH_SHORT).show(); }});return view;
}
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = soy sauce
// Get the child
@Override
public Object getItem(int i) {
return null;
}
// Get the subitem ID
@Override
public long getItemId(int i) {
return 0; }}Copy the code
2.BaseAdapter case optimization
- Optimization 1: Use the RecycleBin View, reduce the read View assignment
- Optimization 2: Use ViewHolder to avoid excessive findViewById operations each time a getView is performed
// Set the ListView effect one by one according to the prepared data source and subitem layout
// Do some details
public class MyAdapter extends BaseAdapter {
private List<Msg> list;
private Context ctx;
public MyAdapter(List<Msg> list, Context ctx) {
this.list = list;
this.ctx = ctx;
}
// Get the number (set the length of ListView)
@Override
public int getCount() {
return list.size();
}
// Get the view (sets the display effect of each item in the ListView) - executes as each view appears
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
// Finish setting the view;
// Convert the layout resource to view
// Parameter 1: the layout resource you want to reference
//RecycleBin
ViewHolder holder;
if(view == null){
Log.e("TAG"."= = = = = =" + i);
// Optimization 1: Use the RecycleBin View to reduce the read View assignment
view = LayoutInflater.from(ctx).inflate(R.layout.item4, null);
holder = new ViewHolder();
holder.profile = view.findViewById(R.id.profile);
holder.nickname = view.findViewById(R.id.nickname);
holder.content = view.findViewById(R.id.content);
holder.like = view.findViewById(R.id.like);
holder.comment = view.findViewById(R.id.comment);
holder.repost = view.findViewById(R.id.repost);
view.setTag(holder);
}else {
// Get the ViewHolder via getTag(), and then pass it directly through the holder. Controls operate directly on the outside of the control
// Avoid the heavy use of the findViewById operation
// In fact, getTag() itself is efficient
holder = (ViewHolder) view.getTag();
}
Msg msg = list.get(i);
/ / avatar
// ImageView profile = view.findViewById(R.id.profile);
holder.profile.setImageResource(msg.getProfile());
/ / nickname
// TextView nickname = view.findViewById(R.id.nickname);
holder.nickname.setText(msg.getNickname());
/ / content
// TextView content = view.findViewById(R.id.content);
holder.content.setText(msg.getContent());
// Whether to like
// ImageView like = view.findViewById(R.id.like);
if(msg.isLike()){
holder.like.setImageResource(R.mipmap.liked);
}else {
holder.like.setImageResource(R.mipmap.like);
}
/ / comment
// ImageView comment = view.findViewById(R.id.comment);
holder.comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ctx, "You clicked on the comments.", Toast.LENGTH_SHORT).show(); }});/ / forwarding
// ImageView repost = view.findViewById(R.id.repost);
holder.repost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ctx, "You hit retweet.", Toast.LENGTH_SHORT).show(); }});return view;
}
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = soy sauce
// Get the child
@Override
public Object getItem(int i) {
return null;
}
// Get the subitem ID
@Override
public long getItemId(int i) {
return 0;
}
//1. Define a class called ViewHolder
//2. Declare the view you want to save as a public property
//3. When to save? When the View is null, the instantiation of the ViewHolder is complete without assigning the spatial attributes
//4. When will it be used? Use it whenever (performance improvement is seen when the view fills with null bits, when scrolling the ListView)
//5. How to use it? When the View is null, a line of code is called after the ViewHolder and internal control properties have been initialized
//view.setTag(holder)
// When view is not null, holder = view.getTag();
static class ViewHolder { public ImageView profile,like,comment,repost; public TextView nickname, content; }}Copy the code