2021SC@SDUSC
In the first blog post, I learned the basic ways to use Android Studio.
The second part mainly uses part of the first week and all the time of the second week to learn the grammar needed for Android development, through which you can finally understand part of the code. Here are some points of knowledge that you summarized from the online tutorials.
The third week will be a detailed code analysis.
Android Studio Development Video Tutorial:
[Tiange] Android Development Video Tutorial The latest version of Android Studio development
Android Development From Beginning to Proficiency (Project Case Edition)
layout
LInearLayout
Main attributes
android:orientation="vertical" android:gravity="center_horizontal|bottom" android:layout_weight="1" // Remaining space allocation percentage, identified by weight, not written as 0
Effect display:
FrameLayout
Show cascading or draggable content
The main content is:
android:foreground="@mipmap/ic_launcher" //Foreground, top picture, will not be overwritten android:foregroundGravity="right|bottom" //Foreground Picture Location Settings
TableLayout
Common properties:
android:collapseColumns="0,2" // Columns to Hide android:stretchColumns="1" // Columns that can be stretched android:shrinkColumns="2" // Columns that can be shrunk <TableRow>...</TableRow> // What is contained in a line, add a line directly with the component without writing
GridLayout
Main attributes:
android:orientation="vertical" // Default sort direction android:rowCount="3" // Maximum number of rows android:columnCount="4" // Maximum number of columns
In another java file:
gridLayout.getChildCount() // Number of sub UI s gridLayout.getChildAt(i) // Return to the View of the sub UI, press index to
Nesting of Layout Manager
1. There can only be one Root Layout Manager, and if more than one is required, include it in one root
2. Root Manager contains xmlns Tags
3. Too much nesting affects performance
Basic UI Components
TextView
ID =>Set a component id, get it by findViewById(), and set it accordingly
Layout_width =>Component width
Layout_height =>component height
wrap_content adaptive size
match_parent is the same as parent
Text =>Set text content
Background =>background color (or background picture)
TextColor =>Set font color
TextStyle =>Set font style
TextSize =>Font Size
Gravity =>Alignment direction of content
The autoLink => autoLink property converts text in the specified format into clickable hyperlinks
DrawableTop => A picture appears at the top of TextView
shadow =>
The shadowColor property is used to set the shadow color, which can be pre-configured in colors.xml.
The shadowRadius property sets the degree of ambiguity, the larger the value, the more ambiguous the shadow;
The shadowDx property sets the offset in the horizontal direction. The larger the value, the more right the shadow moves.
The shadowDy property sets the offset in the vertical direction. The larger the value, the lower the shadow moves.
AutoLink =>Hyperlink web,email,phone,map,all
textColorLink Change Color
DrawableTop => (drawableLeft, drawableRight, drawableBottom): Place a drawable on top (left, right, bottom) of TextView
EditText
Subclasses of TextView
Hint =>hint in text box
TextColorHint =>Set hint prompt text color
inputType =>
"none"//Enter normal characters
"text"//Enter normal characters
"textCapCharacters"//Enter normal characters
"textCapWords"//Word Initial Letter Size
textCapSentences "//First letter size only
"textAutoCorrect"//The first two autocompletions
"textAutoComplete"//The first two autocompletions
"textMultiLine"//Multiline Input
"textImeMultiLine"//Input Method Multiline (not necessarily supported)
"textNoSuggestions"//No prompt
textUri//URI format
"textEmailAddress"//E-mail address format
"textEmailSubject"//Mail Subject Format
textShortMessage//SMS format
"textLongMessage"//Long Message Format
"textPersonName" //Name format
"textPostalAddress"//Postal format
"textPassword"//Password Format
"textVisiblePassword" //Password Visible Format
"textWebEditText"//as text format for web form
textFilter//Text Filter Format
"textPhonetic"//Pinyin Input Format
number//number format
"numberSigned"//Signed Number Format
"numberDecimal"//Floating-point formats that can have decimal points
"phone"//dial keyboard
"datetime"//date+time format
"Date"//date keyboard
"Time"//time keyboard
DrawableLeft =>Draw a picture resource on the left side of the edit box, = Start | also has Top Bottom Right
DrawablePadding =>Picture padding
Lines = > occupy several lines (on display)
Digits =>Set to receive only specified text content
TextAlignment => center, inherit (default, left display), viewStart (left display), viewEnd (right display), textStart (left display), textEnd (right display).
ExtCursorDrawable =>Cursor color
Android:textScaleX =>Text horizontal zoom factor.
Android:typeface => hint font
MaxLength =>Maximum received text length
MaxHeight =>Maximum height of text area
MinHeight =>Minimum height of text area
ScrollHorizontally =>Text exceeded, whether or not a strip appears
Ellipsize =>How to display text when it is too long
"start" omitted at the beginning
end omitted
"Middle" middle omit
"marquee" horselight
// Get text content (Java): EditText editText = findViewById(R.id.et1); editText.getText();
Button
TextView subclass
Click Event Listener:
1. Anonymous Internal Class-MainActivity
Button button = findViewById(R.id.b1); // id of button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Execute Code } });
2.onClick properties
public void myClick(View view){ //Execute Code }
ImageButton
No text attribute
Background setting transparent: android:background = "#0000"
RadioButton
<RadioGroup android:id="@+id/rg1" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2" /> </RadioGroup>
Get Selection Value
Method All Change Options Acquisition (MainActivity):
RadioGroup rg1 = findViewById(R.id.rg1); rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton r = findViewById(checkedId); r.getText(); // Return selected text } });
Method 2 Button acquisition:
Add to the execution code of onClick()
for(int i = 0; i < rg1.getChildCount(); i++) { RadioButton r = (RadioButton) rg1.getChildAt(i); if(r.isChecked()){ Toast.makeText(MainActivity.this,"success" + r.getText(),Toast.LENGTH_SHORT).show(); break; } }
CheckBox
No group required
Listen, add id/cb1 first:
CheckBox cb1; cb1 = findViewById(R.id.cb1); cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(cb1.isChecked()){ cb1.getText(); // Execute Code } } });
DatePicker
public class MainActivity extends AppCompatActivity { DatePicker dp; int y, m, d; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dp = findViewById(R.id.dp); Calendar c = Calendar.getInstance(); y = c.get(Calendar.YEAR); m = c.get(Calendar.MONTH); d = c.get(Calendar.DAY_OF_MONTH); dp.init(y, m, d, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { MainActivity.this.y = year; MainActivity.this.m = monthOfYear; MainActivity.this.d = dayOfMonth; show(); } }); } private void show(){ String s = y + "year" + (m+1) + "month" + d + "day"; Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show(); } }
TimePicker
TimePicker tp; tp = findViewById(R.id.tp); tp.setIs24HourView(true); tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { String s1 = hourOfDay + ":" + minute; Toast.makeText(MainActivity.this, s1, Toast.LENGTH_SHORT).show(); } });
Probably that's all
Advanced UI Components
ProgressBar
Style="" improves the bar style without android:
android:max="100" maximum progress
android:progress="40" current progress
Beautify: Related Links
Simulate progress bar:
public class MainActivity extends AppCompatActivity { private ProgressBar pb; private int p = 0; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb = findViewById(R.id.pb); mHandler = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { if(msg.what == 0x111){ pb.setProgress(p); }else { Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show(); pb.setVisibility(View.GONE); } } }; new Thread(new Runnable() { @Override public void run() { while (true){ p = doWork(); Message m = new Message(); if(p < 100){ m.what = 0x111; // Custom message code, 0x*** mHandler.sendMessage(m); }else{ m.what = 0x110; mHandler.sendMessage(m); break; } } } private int doWork(){ p += Math.random() * 10; try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } return p; } }).start(); } }
SeekBar
ProcessBar subclass
public class MainActivity extends AppCompatActivity { private SeekBar sb; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sb = findViewById(R.id.sb); iv = findViewById(R.id.iv); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { iv.setImageAlpha(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { Toast.makeText(MainActivity.this, "start", Toast.LENGTH_SHORT).show(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { Toast.makeText(MainActivity.this, "end", Toast.LENGTH_SHORT).show(); } }); } }
RatingBar
android:numStars="5" maximum number of stars
android:rating="0" default number of stars
android:stepSize="0.5" star step
android:isIndicator="false" true cannot change the star
ImageView
android:src="" picture file
android:scaleType="" zoom mode
fitXY Fill Stretch
center centered, no zoom, small intercept
Center Crop locks aspect ratio zoom, intercepts display
Center Inside locks aspect ratio zoom for full display
fitCenter same as above, in the center, similar to fitEnd bottom, fitStart top
martix matrix drawing
android:adjustViewBounds="true" self-adjusting picture layout requires wrap for layout
android:maxWidth="90dp" maximum width
android:maxHeight="90dp" maximum height
android:tint="#aaff0000" filter, mask
ImageSwitcher
There are click and slide switches
GridView
android:numColumns="" number of columns
Adapter
Divided into ArrayAdapter
SimpleAdapter
SimpleCursorAdapter
BaseAdapte
Spinner
android:entries="" list content
Define method:
//(1) Array resource file*.xml <?xml version="1.0" encoding="utf-8"?> <resources>
Activity
destroy restarts when the screen flips
Switch Activity
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Main2Activity.class); startActivity(intent); } });
End (Return) Activity
finish()
Refresh:
onCreate(null)
Transferring data using Bundle
intent
attribute
Component name
SetComponent (ComponentName (package name, class name))
Switch Acitvity using ComponentName
Intent intent = new Intent(); ComponentName componentName = new ComponentName("com.example.intent", "com.example.intent.Detail")
Action s and Data
Set up click monitoring, call and text messaging
Extras
putExtras()
getExtras()
Flags
intent.setFlags(intent.FLAG_ACTIVITY_NO_HISTORY); //User left auto-off
Intent Kinds
(1) Explicit Intent
Specify switching objects
(2) Implicit Intent
No object specified
For example: Open Baidu Home Page
Intent intent = new Intent(); intent.setAction(intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.baidu.com"));
Intent filter
Set in AndroidManifest.xml by markup
Event
Listener-based events
Course setup involves many times, no more details
Callback-based events
onTouchEvent()
onKeyDown()
onKeyUp()
Physical key events
onKeyDown()
onKeyUp()
onKeyLongPress()
Touch screen events
Click -
Click Event Listener
button.setOnClickListener(new View.OnClickListener() {}
Long press
button.setOnLongClickListener(new View.OnLongClickListener() {}
touch
MontionEvent saves touch coordinates, time, etc.
Pictures Following Mouse Move
Single click
public boolean onTouch(View v, MotionEvent event) { //Functional Code return false; // false is a click event ) }
Gesture Detection
onDown Press
onFling Drag Over
onLongPress Long Press
onSingleTapUp Tap
onScroll
onShowPress
_Sliding effect with onFling
// You can also create OnGestureListener with a single class public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener { Animation[] animations = new Animation[4]; final int distance = 50; private int[] images = new int[]{R.drawable.i1,R.drawable.i2,R.drawable.i3,R.drawable.i4}; GestureDetector gestureDetector; ViewFlipper viewFlipper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gestureDetector = new GestureDetector(MainActivity.this,this); // Here the separate this is OnGestureListener viewFlipper = findViewById(R.id.flipper); for(int i = 1; i < images.length; i++){ ImageView imageView = new ImageView(this); imageView.setImageResource(images[i]); viewFlipper.addView(imageView); } animations[0] = AnimationUtils.loadAnimation(this, R.anim.slide_in_left); animations[1] = AnimationUtils.loadAnimation(this, R.anim.slide_in_right); animations[2] = AnimationUtils.loadAnimation(this, R.anim.slide_out_left); animations[3] = AnimationUtils.loadAnimation(this, R.anim.slide_out_right); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(e1.getX() - e2.getX() < distance){ viewFlipper.setInAnimation(animations[0]); viewFlipper.setOutAnimation(animations[2]); viewFlipper.showNext(); return true; }else if (e1.getX() - e2.getX() > distance){ viewFlipper.setInAnimation(animations[1]); viewFlipper.setOutAnimation(animations[3]); viewFlipper.showPrevious(); return true; } return false; } @Override public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } }
Subsequent data storage, handler, service, mvvn, and so on, will be analyzed in conjunction with specific code.