Android Android Development Quick Start

It’s better to eat with Tian Ge’s video: [Tian Ge] Android development video tutorial latest version Android Studio development

UI components (controls)

layout manager

LinearLayout (linear layout)

Nestable

Most commonly used properties

id plays the role of marking the layout

layout_width [wrap_content selects size based on content, match_parent matches parent, specific value (unit - dp)]

layout_height

layout_weight weight, allocate the remaining space of the parent according to the weight ratio. When two child elements are arranged horizontally, and the width of each child element is set to 0dp, and the weight is set to 1, the two child elements will equally divide the width of the parent, each accounting for half

background

layout_margin margin

layout_padding padding

orientation sets the direction of linear layout

gravity sets internal element alignment

relativelayout (relative layout)

layout_toLeftOf is set to the left of xx

layout_toRightOf is set to the right of xx

layout_alignBottom is set at the bottom of xx

layout_alignParentBottom sets itself to the bottom of the parent element

layout_below is set below xx

Steps to use controls

  1. Declare the control in MainActivity (the setting method of the startup page activity, you need to add the intent-filter tag to the target activity

    <activity android:name=".MainActivity">
    	<intent-filter>
    		<action android:name="android.intent.action.MAIN"/>
    		<category android:name="android.intent.category.LAUNCHER"/
    	</intent-filter>
    </activity>
    

  2. find control

  3. type conversion

  4. Set click event

(

  1. Create target activity
  2. Declare this activity in Androidmanifest.xml
  3. Design in the target activity

)

private Button mBtn3;//1.在MainActivity里声明控件
@Override
protected void onCreate(Bundle savedInstancestate){
    
    
	super.onCreate(savedInstancestate);
	setContentview(R.layout.activity_button);
	mBtn3 = (Button)findviewById(R.id.btn_3);//2.找到控件 3.类型转换
	mBtn3.setonclickListener(new View.OnclickListener(){
    
    //设置点击事件
		@Override
		public void onclick(View v){
    
    
			Toast.makeText(ButtonActivity.this,"btn3被点击了"Toast.LENGTH_SHORT).show();
});

Optimization of setting up click event steps

  1. Customize the OnClick class, which implements the View.OnClickListener interface
  2. Override the onClick method in the OnClick class, and the parameter is the View type
  3. The onClick method needs to declare an Intent object, and then use switch to determine the ID of the incoming View object. Different IDs correspond to different Intent objects.
  4. Declare the method setListeners in the main class, create a new object of the custom class OnClick inside, and place this object in the setOnClickListener method of each button.
  5. Find the object of each button in the Oncreat method, and finally call the setListeners method once
public class MainActivity extends AppCompatActivity {
    
    

    private Button mBtnUI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnUI = (Button) findViewById(R.id.btn_ui);
        OnClick onClick = new OnClick();
        mBtnUI.setOnClickListener(onClick);
    }

    class OnClick implements View.OnClickListener{
    
    
        @Override
        public void onClick(View v) {
    
    
            Intent intent = null;
            switch (v.getId()){
    
    
                case R.id.btn_ui:
                    intent = new Intent(MainActivity.this,UIActivity.class);
                    break;
            }
            startActivity(intent);
        }
    }
}

TextView

Application scenarios

  1. Text size, color

id

layout_width text width

layout_height text height

text text content, it is recommended to quote the string defined in string.xml

textColor font color

textSize font size (unit - sp)

  1. Cannot be displayed using...

maxLines maximum number of lines

ellipsize [start/middle/end/marquee/none] end ends with...

  1. character+icon

The icon should be placed under the drawable

drawableXxxxx = picture src, select the picture to be placed on the x side of the text in TextView

drawableRight selects the picture to be placed to the right of the text in TextView

drawablePadding selects the padding of the image

  1. Center line, underline

Need to be implemented through java code

center line

private Textview mTv4;//声明控件
@Override
protected void onCreate(Bundle savedInstanceState){
    
    
	super.onCreate(savedInstanceState);
	setContentview(R.layout.activity_text_view);
    
	mTv4 = (Textview)findViewById(R.id.tv_4);//找到id对应的控件
	mTv4.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//设置中划线,此时会有锯齿
	mTv4.getPaint().setAntiAlias(true);//去除锯齿
}

Underline

private Textview mTv5;//声明控件
@Override
protected void onCreate(Bundle savedInstanceState){
    
    
	super.onCreate(savedInstancestate);
	setContentview(R.layout.activity_text_view);

    mTv5 = (Textview)findViewById(R.id.tv_5);//指定控件
	mTv5.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
}

Setting the underline through HTML eliminates the need to declare the specific content of the text attribute in TextView.

private TextView mTv6= (TextView) findViewById(R.id.tv_6)
mTv6.setText(Html.fromHtml("<u>李在赣神魔</u>"));
  1. Marquee text effect

singleLine single line display, set to true

ellipsize sets the display effect of redundant text. It should be set to marquee here.

marqueeRepeatLimit The number of text cycles, here set to marquee_forever

After setting these, you also need to set focus-related matters.

focusable set to true

focusableInTouchMode is set to true

Specific code:

<TextView
	android:id="@+id/tv_7"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="天哥在奔跑天哥在奔跑天哥在奔跑天哥在奔跑"
	android:textColor="#000000"
	android:textsize="24sp"
	android:singleLine="true"
	android:ellipsize="marquee"
	android:marqueeRepeatLimit="marquee_forever"
	android:focusable="true"
	android:focusableInTouchMode="true"/>

Button (subclass of TextView)

Other derived controls of Button: ToggleButton, Switch

You need to declare a private Button in mainactivity and specify the target button control. Return the view object through the findViewById() method and force it to Button

private Button mBtnTextView =(Button)findViewById(R.id.btn_textview)

Unique properties

textAllCaps="false" turns off the default setting of all letters in uppercase and displays them according to the actual text

Application scenarios

  1. font size

textSize (unit-sp)

  1. Custom background shape

background specifies a custom effect. You need to create the shape root element file in the drawable.

Set rounded corners button

drawable resource file contents

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">//设置按钮形状为矩形
    <solid android:color="#FF9900"></solid>//设置颜色为橙色
    <corners android:radius="10dp"></corners>//设置圆角

</shape>

Set the border and fill the space inside

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">//设置按钮形状为矩形
    <stroke //描边效果
    android:width="1dp" //描边线 的宽度
    android:color="#FF9900"></stroke>//设置颜色为橙色
    <corners android:radius="10dp"></corners>//设置圆角

</shape>
  1. Customized press effect
<?xml version="1.0"encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_pressed="true">
		<shape>
			<solid android:color="#AA6600"/>
			<corners android:radius="5dp"/>
		</shape>
	</item>
	<item android:state_pressed="false">
		<shape>
			<solid android:color="#FF9900"/>
			<corners android:radius="5dp"/>
		</shape>
	</item>
</selector>
  1. Click event (gray pop-up window pops up at the bottom of the phone)

method one:

onClick="showToast" This line of attributes means that after clicking, the showToast() method of the Activity is called.

You need to set this property in the Button and write the specific content of the method in the ButtonActivity class, imitating the following code

public class ButtonActivity extends AppCompatActivity{
    
    
	@Override
	protected void onCreate(Bundle savedInstancestate){
    
    
		super.onCreate(savedInstancestate);
		setContentview(R.layout.activity_button);
	}	
	public void showToast(View view){
    
    
		Toast.makeText(this,"我被点击了"Toast.LENGTH_SHORT).show();
    }
}

Method 2: Set a click event for the button (commonly used)

Declare a button object in the activity and point to the existing button. Call setOnclickListener() of this object. The parameter passed in is an anonymous class anonymous object – new View.OnClickListener(), and override the onClick() method in the anonymous object.

private Button mBtn3;
@Override
protected void onCreate(Bundle savedInstancestate){
    
    
	super.onCreate(savedInstancestate);
	setContentview(R.layout.activity_button);
	mBtn3 = (Button)findviewById(R.id.btn_3);
	mBtn3.setonclickListener(new View.OnclickListener(){
    
    
		@Override
		public void onclick(View v){
    
    
			Toast,makeText(ButtonActivity.this,"btn3被点击了"Toast.LENGTH_SHORT).show();
});

TextView can also set click events

EditText (subclass of TextView)

– An input text box control

Commonly used (unique) attributes

textColor The color of the text

hint Gray text used for prompts such as "Please enter username"

inputType = “textPassword” sets the entered password to dark text

inputType="number" specifies that the input characters are numbers, and clicking the text box will pop up the numeric keyboard

drawableLeft sets a picture to the left of the text box

drawablePadding sets the padding of the image

maxLines The maximum number of lines is usually set to 1

The method of customizing background is the same as Button to set click event.

Create login interface + listen for events (listening controls)

Two edittext usernames and passwords, and a button login button

The effect of successful login requires setting up listening events. The steps are to declare in the current activity, specify the control, and set the click effect. You can refer to the second method of click event in Button application scenario.

Monitor the input username information on the console

private EditText mEtUserName;
mEtUserName = (EditText)findViewById(R.id.et_1);
mEtUserName.addTextChangedListener(new TextWatcher(){
    
    
	@Override
	public void beforeTextChanged(CharSequence s,int start,int count,int 			after){
    
    
		}
	@Override
	public void onTextChanged(CharSequence s,int start,int before,int 			count){
    
    
				Log.d("edittext",s.tostring());//在控制台监听用户输入的信息
		}
	@Override
	public void afterTextChanged(Editable s){
    
    
		}
})

RadioButton (Button child)

illustrate:

  1. If there is more than one RadioButton group, it must be wrapped by RadioGroup.
  2. RadioGroup is a radio selection. Even if each RadioButton has a background, the effect will only be displayed on the selected button.

Commonly used (unique) attributes

textSize button text size unit-sp

checked The default selected state (provided that RadioButton has an id, otherwise it will be invalid)

button="@null" sets the button's circle to disappear

RadioGroup Properties

orientation internal button arrangement

Custom style

Similar to the background of button, but different↓

Attributes in the item tag in the selector

state_checked = "true" button checked state

stroke tag stroke effect

Listen for events

Insert image description here

CheckBoxCheckBox

  1. Multiple checkboxes do not need to be wrapped
  2. Each checkbox can be checked or deselected

Common properties

text

textSize --sp

textColor

button="background_src" custom checkbox

item attribute

state_checked = "true" The checked state is

state_checked = "false" means the selected state is

Listen for events

Insert image description here

ImageView

Common properties

background background (color/image)

src sets a picture above the background

scaleType src image scaling type in the control (fitXY: fills the control, the aspect ratio may change; fitCenter: maintains the aspect ratio scaling until it can be fully displayed; centerCrop: maintains the aspect ratio until it completely covers the control, and crops the display )

Common methods of ImageVIew object

setImageResource sets the picture of the picture view

How to load network images (using the third-party image loading library glide)

Important note: When the app needs to apply network files, you need to declare the use-permission tag in the AndroidManifest.xml file.

Import method

Method 1: Search for the glide library on github, download the library and put it in the libs folder.

Method 2: Or use gradle management to copy the repositories and dependencies introduced in the readme file in github to gradle. The second compile in dependencies does not need to be copied. Note: When the app needs to apply network files, the use-permission tag needs to be declared in the AndroidManifest.xml file.

Simple use case
public class ImageViewActivity extends AppCompatActivity {
    
    

    private ImageView mIv4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view);
        mIv4 = (ImageView) findViewById(R.id.iv_4);//找到控件,mIv4指定控件
        Glide.with(this).load("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png").into(mIv4);//加载图片,把网络图片地址放在load()里面
    }
}

ListView ListView (outdated, confused)

Custom Activity

  1. Create ListViewActivity, the parent class is Activity. Declare the custom class in AndroidManifest.xml
  2. Override methods onCreat(), setContentView (layout.xml from R.layout.new)
  3. In the new xml, design a specific ListView

Custom ListView

  1. Customize the Adapter first
  2. Write a layout,

Common properties

listSelector specifies the selector modification file

Custom Adapter interface

  1. Customized MyLIstAdapter, inherited from BaseAdapter.

  2. Write a constructor and override the getView method (which is used to customize how each grid is implemented)

    private Context mContext;
    private LayoutInflatert mLayoutInflatert;
    
    public MyListAdapter(Context context){
          
          
    	this.mContext=context;
        mLayoutInflatert=LayoutInflater.from(comtext);
    }
    
    get view()
    

Click event (long press or click)

Insert image description here

GridView (obsolete, similar to ListView)

The difference between APPCompatActivity and Activity: appcompatactivity has the top application name, activity does not

Common properties

numColumns controls the number of columns

horizontalSpacing horizontal grid spacing

verticalSpacing vertical grid spacing

Adapter interface

resemblance

click event

resemblance

ScrollViewScrollView

Vertical scrolling: ScrollView

There can only be one child element

Wrap controls including LinearLayout in the ScrollView control to achieve vertical scrolling

Horizontal scrolling: HorizontalScrollView

There can only be one child element

Wrap controls including LinearLayout in HorizontalScrollView control to achieve vertical scrolling

RecyclerView control (jumped)

Used to replace ListView, GridView, ScrollView

RecyclerViewi can flexibly display large data sets. The reuse management of views is better than ListView. It can display lists, grids, waterfalls, etc., and different ViewHolders can realize the diversified functions of items.
However, it will be a little more troublesome to use, and there is no onItemClickListener-like listening event like ListView, so developers need to implement it themselves.

Introduce the RecyclerView package before use : add it in the dependencies of build.gradle

compile com.android.support:design:25.3.1
//会变换,需要上网搜索查询

LinearRecyclerViewActivity

WebView control

Load web page

Load URL (HTML file from the web)

webview.loadUrl(“http://www.m.baidu.com”)

If it is not loaded, it is because the js code is not loaded by default and needs to be set.

mWv.Main.getSettings().setJavaScriptEnable

If you jump to the browser and do not open the web page in the application, you need to set it up.
mWvMain.setWebnViewClient(new MyWebViewClient()); 

class MyWebViewClient extends WebViewClient{
    
    //内部类
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    
    
            view.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
    
    
            super.onPageStarted(view, url, favicon);
            Log.d("WebView","onPageStarted...");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
    
    
            super.onPageFinished(view, url);
            Log.d("WebView","onPageFinished...");
//            mWvMain.loadUrl("javascript:alert('hello')");
            mWvMain.evaluateJavascript("javascript:alert('hello')",null);
        }
    }
When returning to the web page, you need to rewrite a method to directly exit the activity.
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    
    
        if(keyCode == KeyEvent.KEYCODE_BACK && mWvMain.canGoBack()){
    
    
            mWvMain.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
Load the local assets folder (put some files that do not need to be compiled)

webview.loadUrl(“file:///android_asser/test.html”)

The assets folder is created in the sr0c-main directory and creates file

Load html code

webview.loadData();

webview.loadDataWithBaseURL();

Web page forward and backward

webview.canGoBack();

webview.goBack();

webview.canGoForward();

webview.goForward();

webview.canGoVackOrForward(int steps)

Press the return key to exit the current Activity by default. If you want to go back to the page in VebView
@Override
public boolean onKeyDown(int keyCode,KeyEvent event){
    
    
	if ((keyCode =KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
    
    
		webview.goBack();
		return true;
		}
        return super.onKeyDown(keyCode,event);
}

UI component pop-up component

Toast

Toast is a message prompt component that can be used to design Button click feedback prompt effects.

Set display location

Default, centered, with picture (customized)

Create a custom class OnClick to implement View.OnClickListener

class OnClick implements View.OnClickListener{
    
    
        @Override
        public void onClick(View v) {
    
    
            switch (v.getId()){
    
    
                case R.id.btn_toast_1://默认效果
                    Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
                    break;
                case R.id.btn_toast_2://居中效果,makeText返回的是一个Toast类型对象,对这个对象进行操作可以改变Toast调用show()时显示的样式
                    Toast toastCenter = Toast.makeText(getApplicationContext(),"居中Toast",Toast.LENGTH_LONG);
                    toastCenter.setGravity(Gravity.CENTER,0,0);
                    toastCenter.show();
                    break;
                case R.id.btn_toast_3://自定义图片效果
                    Toast toastCustom = new Toast(getApplicationContext());
                    LayoutInflater inflater = LayoutInflater.from(ToastActivity.this);
                    View view = inflater.inflate(R.layout.layout_toast,null);
                    ImageView imageView = (ImageView) view.findViewById(R.id.iv_toast);
                    TextView textView = (TextView) view.findViewById(R.id.tv_toast);
                    imageView.setImageResource(R.drawable.icon_smile);
                    textView.setText("自定义Toast");
                    toastCustom.setView(view);
                    toastCustom.setDuration(Toast.LENGTH_LONG);
                    toastCustom.show();
                    break;
                case R.id.btn_toast_4:
                    ToastUtil.showMsg(getApplicationContext(),"包装过的Toast");
                    break;
            }
        }
    }

Customize display content

Customize display content through Toast object

case R.id.btn_toast_3:
                    Toast toastCustom = new Toast(getApplicationContext());
                    LayoutInflater inflater = LayoutInflater.from(ToastActivity.this);
                    View view = inflater.inflate(R.layout.layout_toast,null);
                    ImageView imageView = (ImageView) view.findViewById(R.id.iv_toast);
                    TextView textView = (TextView) view.findViewById(R.id.tv_toast);
                    imageView.setImageResource(R.drawable.icon_smile);
                    textView.setText("自定义Toast");
                    toastCustom.setView(view);
                    toastCustom.setDuration(Toast.LENGTH_LONG);
                    toastCustom.show();
                    break;

Common methods/constructors of Toast objects

Constructor uses:

Toast toastCustom = new Toast(getApplicationContext());

method:

setView(view) sets the view of Toast

setDuration sets the duration of Toast’s stay

show displays Toast content

cancel Clicking the toast multiple times will only superimpose the effect once (higher versions of the API do not need to consider this)

illustrate:

The setView method needs to pass in a view, which needs to be returned by calling the inflate method through a LayoutInflater object. In addition, you can also customize the display content of these controls by specifying imageView and calling methods through imageView.

Simple encapsulation, public utility class ToastUtil

public class ToastUtil {
    
    
    public static Toast mToast;
    public static void showMsg(Context context,String msg){
    
    
        if(mToast == null){
    
    
            mToast = Toast.makeText(context,msg,Toast.LENGTH_LONG);
        }else{
    
    
            mToast.setText(msg);
        }
        mToast.show();
    }
}

Using ToastUtil, this case will only superimpose the effect once, even if the cnacel method is not used

case R.id.btn_toast_4:
                    ToastUtil.showMsg(getApplicationContext(),"包装过的Toast");
                    break;

AlertDialog alert dialog box

AlertDialog.Builder common methods

setTitle sets the dialog title

setMessage sets the dialog box content

setIcon sets the dialog icon

setPositiveButton sets the positive option button (onClick sets the click event of the button)

setNeutralButton sets the neutral button

setNegativeButton sets the negative button

The setItems parameter can be an array, set the content of the button, and can set the click event

setSingleChoiceItems sets single selection (array, array index of the content to be selected, click event)

setCancelable(false) Setting - In addition to clicking on the option, the dialog box will not disappear when you click elsewhere. After setting this, you need to call dismiss in onClick after calling the show method to achieve the effect of disappearing after clicking on the option.

Default style

step:

case R.id.btn_dialog1:
                    AlertDialog.Builder builder = new AlertDialog.Builder(DialogActivity.this);
//链式调用,设置对话框显示效果,以及点击事件
                    builder.setTitle("请回答").setMessage("你觉得课程如何?")
                            .setIcon(R.drawable.icon_user)
                            .setPositiveButton("棒", new DialogInterface.OnClickListener() {
    
    
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
    
    
                                    ToastUtil.showMsg(DialogActivity.this, "你很诚实");
                                }
                            }).setNeutralButton("还行", new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            ToastUtil.showMsg(DialogActivity.this, "你再瞅瞅~");
                        }
                    }).setNegativeButton("不好", new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            ToastUtil.showMsg(DialogActivity.this, "睁眼说瞎话");
                        }
                    }).show();
                    break;

Radio style

setSingleChoiceItems()

Style one:

case R.id.btn_dialog2:
                    final String[] array2 = new String[]{
    
    "男", "女"};
                    AlertDialog.Builder builder2 = new AlertDialog.Builder(DialogActivity.this);
                    builder2.setTitle("选择性别").setItems(array2, new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            ToastUtil.showMsg(DialogActivity.this, array2[which]);
                        }
                    }).show();
                    break;

Style 2: You can select a value by default

case R.id.btn_dialog3:
                    final String[] array3 = new String[]{
    
    "男", "女"};
                    AlertDialog.Builder builder3 = new AlertDialog.Builder(DialogActivity.this);
                    builder3.setTitle("选择性别").setSingleChoiceItems(array3, 1, new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            ToastUtil.showMsg(DialogActivity.this, array3[which]);
                            dialog.dismiss();
                        }
                    }).setCancelable(false).show();
                    break;

Multiple selection style

setMultiChoiceItems()

case R.id.btn_dialog4:
                    final String[] array4 = new String[]{
    
    "唱歌", "跳舞","写代码"};
                    boolean[] isSelected = new boolean[]{
    
    false,false,true};
                    AlertDialog.Builder builder4 = new AlertDialog.Builder(DialogActivity.this);
                    builder4.setTitle("选择兴趣").setMultiChoiceItems(array4, isSelected, new DialogInterface.OnMultiChoiceClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
    
    
                            ToastUtil.showMsg(DialogActivity.this,array4[which]+":"+isChecked);
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            //
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    

                        }
                    }).show();
                    break;

Custom style (login style)

case R.id.btn_dialog5:
                    AlertDialog.Builder builder5 = new AlertDialog.Builder(DialogActivity.this);
                    View view = LayoutInflater.from(DialogActivity.this).inflate(R.layout.layout_dialog,null);
                    EditText etUserName = (EditText) view.findViewById(R.id.et_username);
                    EditText etPassWord = (EditText) view.findViewById(R.id.et_password);
                    Button btnLogin = (Button) view.findViewById(R.id.btn_login);
                    btnLogin.setOnClickListener(new View.OnClickListener() {
    
    
                        @Override
                        public void onClick(View v) {
    
    
                            //
                        }
                    });
                    builder5.setTitle("请先登录").setView(view).show();
                    break;

ProgressBar&ProgressDialog

ProgressBar

Common properties

style The style of the progress bar. The default is @style/Widget.Material.ProgressBar. There are many styles. You can customize a style in res-values-style, such as

    <style name="MyProgressBar">
        <item name="android:indeterminateDrawable">@drawable/bg_progress</item>//引用一个自定义的drawable文件
    </style>

Among them, widget.progressbar.horizontal is a long progress bar with progress

progress sets the progress of the progress bar

secondaryProgress sets the secondary progress of the progress bar

progressDrawable Designs a custom view of the progress bar

visibility controls whether the progress bar is visible or invisible

indetertminateDrawable="@drawable/bg_progress" Replace with custom drawable file (

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/icon_progress"//一个图片
    android:pivotX="50%" //设置水平转轴中心
    android:pivotY="50%">//设置垂直

</animated-rotate>

ProgressDialog

Insert image description here

Common methods of ProgressDialog class

Constructor:

ProgressDialog progressDialog = new ProgressDialog(ProgressActivity.this);

method:

setProgressStyle sets the style, which can be set to a progress bar

setTitle sets the title

setMessage set content

setOnCancelListener sets the listener for cancellation behavior

setCancelable="false" The setting cannot be canceled

show show progressdialog

setButton set button

Example 1

Insert image description here

private Button mBtnStart,mBtnProgressDialog1,mBtnProgressDialog2;
mBtnProgressDialog1 = (Button) findViewById(R.id.btn_progress_dialog1);
mBtnProgressDialog1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                ProgressDialog progressDialog = new ProgressDialog(ProgressActivity.this);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("正在加载");
                progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    
    
                    @Override
                    public void onCancel(DialogInterface dialog) {
    
    
                        ToastUtil.showMsg(ProgressActivity.this,"cancel...");
                    }
                });
                progressDialog.setCancelable(false);
                progressDialog.show();
            }
        });
Example 2

Insert image description here

     mBtnProgressDialog2.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                ProgressDialog progressDialog = new ProgressDialog(ProgressActivity.this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setTitle("提示");
                progressDialog.setMessage("正在下载...");
                progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "棒", new DialogInterface.OnClickListener() {
    
    //设置按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
    
    
                        //
                    }
                });
                progressDialog.show();
            }
        });

Custom Dialog (?)

Set dialog shape (shape)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">//矩形
    <solid android:color="@color/colorWhite"/>//填充颜色
    <corners android:radius="10dp"/>//圆角
</shape>

CustomDialogActivity page

public class CustomDialogActivity extends AppCompatActivity {
    
    

    private Button mBtnDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);
        mBtnDialog = (Button) findViewById(R.id.btn_custom_dialog);
        mBtnDialog.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                CustomDialog customDialog = new CustomDialog(CustomDialogActivity.this);
                customDialog.setTitle("提示").setMessage("确认删除此项?")
                .setCancel("取消", new CustomDialog.IOnCancelListener() {
    
    
                    @Override
                    public void onCancel(CustomDialog dialog) {
    
    
                        ToastUtil.showMsg(CustomDialogActivity.this,"cancel...");
                    }
                }).setConfirm("确认", new CustomDialog.IOnConfirmListener() {
    
    
                    @Override
                    public void onConfirm(CustomDialog dialog) {
    
    
                        ToastUtil.showMsg(CustomDialogActivity.this,"confirm...");
                    }
                }).show();
            }
        });
    }
}

Custom CustomDialog class

public class CustomDialog extends Dialog implements View.OnClickListener{
    
    

    private TextView mTvTitle,mTvMessage,mTvCancel,mTvConfirm;

    private String title,message,cancel,confirm;

    private IOnCancelListener cancelListener;

    private IOnConfirmListener confirmListener;

    public CustomDialog(@NonNull Context context) {
    
    
        super(context);
    }

    public CustomDialog(@NonNull Context context,int themeId) {
    
    
        super(context,themeId);
    }

    public CustomDialog setTitle(String title) {
    
    
        this.title = title;
        return this;
    }

    public CustomDialog setMessage(String message) {
    
    
        this.message = message;
        return this;
    }

    public CustomDialog setCancel(String cancel,IOnCancelListener listener) {
    
    
        this.cancel = cancel;
        this.cancelListener = listener;
        return this;
    }

    public CustomDialog setConfirm(String confirm,IOnConfirmListener listener) {
    
    
        this.confirm = confirm;
        this.confirmListener = listener;
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_custom_dialog);
        //设置宽度
        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        Point size = new Point();
        d.getSize(size);
        p.width = (int)(size.x * 0.8); //设置dialog的宽度为当前手机屏幕的宽度*0.8
        getWindow().setAttributes(p);

        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvMessage = (TextView) findViewById(R.id.tv_message);
        mTvCancel = (TextView) findViewById(R.id.tv_cancel);
        mTvConfirm = (TextView) findViewById(R.id.tv_confirm);
        if(!TextUtils.isEmpty(title)){
    
    
            mTvTitle.setText(title);
        }
        if(!TextUtils.isEmpty(message)){
    
    
            mTvMessage.setText(message);
        }
        if(!TextUtils.isEmpty(cancel)){
    
    
            mTvCancel.setText(cancel);
        }
        if(!TextUtils.isEmpty(confirm)){
    
    
            mTvConfirm.setText(confirm);
        }
        mTvCancel.setOnClickListener(this);
        mTvConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.tv_cancel:
                if(cancelListener != null){
    
    
                    cancelListener.onCancel(this);
                }
                dismiss();
                break;
            case R.id.tv_confirm:
                if(confirmListener != null){
    
    
                    confirmListener.onConfirm(this);
                }
                dismiss();
                break;
        }
    }

    public interface IOnCancelListener{
    
    
        void onCancel(CustomDialog dialog);
    }

    public interface IOnConfirmListener{
    
    
        void onConfirm(CustomDialog dialog);
    }
}

PopupWindow popup window

Can be used in the function of selecting subjects

Insert image description here

Common methods

setOutsideTouchable = "true" Set click outside to close the pop-up window

setFocusable =“true”

showAsDropDown sets the control under which the window appears.

showAtLocation

Example

activity file:

public class PopupWindowActivity extends AppCompatActivity {
    
    

    private Button mBtnPop;
    private PopupWindow mPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_popup_window);
        mBtnPop = (Button) findViewById(R.id.btn_pop);
        mBtnPop.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                View view = getLayoutInflater().inflate(R.layout.layout_pop,null);
                TextView textView = (TextView) view.findViewById(R.id.tv_good);
                textView.setOnClickListener(new View.OnClickListener() {
    
    
                    @Override
                    public void onClick(View v) {
    
    
                        mPop.dismiss();
                        //do something...
                        ToastUtil.showMsg(PopupWindowActivity.this,"好");
                    }
                });
                mPop = new PopupWindow(view,mBtnPop.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
                mPop.setOutsideTouchable(true);
                mPop.setFocusable(true);
                mPop.showAsDropDown(mBtnPop);
            }
        });
    }
}

Page design xml file

<?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"
    android:background="@drawable/bg_dropdown">

    <TextView
        android:id="@+id/tv_good"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorGrayDark"
        android:text="好"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="@color/colorGrayDark"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorGrayDark"
        android:text="还行"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="@color/colorGrayDark"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorGrayDark"
        android:text="不好"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"/>

</LinearLayout>

Indispensable Activities and Fragments

Activity creation trilogy

step:

1. Create a new class that inherits Activity or its subclasses (v7.appcompatactivity)

2. Declare in AndroidManifest. If you want to change the title of the page, you need to set the label attribute in the activity tag here.

3. Create a layout and set it in onCreat of the activity

Activity attribute

screenOrientation display direction, fixed vertical or fixed vertical; defaults to follow the change of the mobile phone

label title

theme subject

launchMode launch mode

The intent-filter tag is set to the startup page.

taskAffinity=".abcdef" sets the name of the task stack

<intent-filter>
	<action android:name="android.intent..action.MAIN"/
	<category android:name="android.intent.category.LAUNCHER"/
</intent-filter>

How to customize a page title bar

  1. Set the activity attribute theme = [noactionbar has no effect]. If you want to set the same theme for each page, you can set the theme effect = noactionbar in the application tag.

Activity life cycle

Insert image description here

How to determine what state the current activity is in (output information through the console)

public class LifeCycleActivity extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        Log.d("LifeCycle","----onCreate----");
    }

    @Override
    protected void onStart() {
    
    
        super.onStart();
        Log.d("LifeCycle","----onStart----");
    }

    @Override
    protected void onResume() {
    
    
        super.onResume();
        Log.d("LifeCycle","----onResume----");
    }

    @Override
    protected void onPause() {
    
    
        super.onPause();
        Log.d("LifeCycle","----onPause----");

    }

    @Override
    protected void onStop() {
    
    
        super.onStop();
        Log.d("LifeCycle","----onStop----");
    }

    @Override
    protected void onRestart() {
    
    
        super.onRestart();
        Log.d("LifeCycle","----onRestart----");
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        Log.d("LifeCycle","----onDestroy----");
    }
}
  • The first time you enter the activity will proceed, oncreat onstart onresume
  • Other places are occupied, causing the activity to be in the background. OnPause onStop is called.
  • onDestory when closing activity

Activity jump and data transfer

Explicit jump and implicit jump

Usually use the method of displaying 1

Can implicit jump jump to other software? Jump from the software page to the phone call page?

mBtnJump.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                //显式1
                Intent intent = new Intent(AActivity.this, BActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("name", "天哥");
                bundle.putInt("number", 88);
                intent.putExtras(bundle);
                startActivity(intent);
//                startActivityForResult(intent, 0);

                //显式2
//                Intent intent = new Intent();
//                intent.setClass(AActivity.this,BActivity.class);
//                startActivity(intent);

                //显式3
//                Intent intent = new Intent();
//                intent.setClassName(AActivity.this,"com.skypan.helloworld.jump.BActivity");
//                startActivity(intent);

                //显式4
//                Intent intent = new Intent();
//                intent.setComponent(new ComponentName(AActivity.this,"com.skypan.helloworld.jump.BActivity"));
//                startActivity(intent);

                //隐式
//                Intent intent = new Intent();
//                intent.setAction("com.skypan.test.BActivity");
                //setAction的内容是我们再AndroidManifest中给这个Activity设置的action,可以是任何值,起标识作用;然后设置category为default,具体看下面
//                startActivity(intent);
            }
        });
<activity android:name=".jump.BActivity"
	android:label="B">
	<intent-filter>
		<action android:name="com.skypan.test.BActivity"/>
		<category android:name="android.intent.category.DEFAULT"/>
	</intent-filter>
</activity>

Data transfer between activities

//传出:intent:意图
Intent intent = new Intent(AActivity.this, BActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("name", "天哥");
                bundle.putInt("number", 88);
                intent.putExtras(bundle);
                startActivity(intent);
//接收:
Bundle bundle = getIntent().getExtras();
        String name = bundle.getString("name");
        int number = bundle.getInt("number");

startActivity: Start Activity and return the result after completion

Page A goes to page B. When page B needs to transfer data to page A, you need to use startActivityForResult(intent,0);

//A页面
startActivityForResult(intent, 0);  

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);
        Toast.makeText(AActivity.this, data.getExtras().getString("title"), Toast.LENGTH_LONG).show();
    }
//B页面
  mBtnFinish.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                Intent intent = new Intent();
                Bundle bundle1 = new Bundle();
                bundle1.putString("title","我回来了");
                intent.putExtras(bundle1);
                setResult(Activity.RESULT_OK,intent);
                finish();
            }
        });

4 ways to start Activity

Activity's android:launchMode attribute (set in AndroidManifest):

  • standard: standard mode
  • singleTop: task stack top reuse mode
  • singleTask: reuse mode within task stack
  • singleInstance: global singleton mode

standard

Activity is managed by the task stack. Every time an Activity is started, it will be put into the stack. Pressing the return key will remove an Activity from the top of the stack.

standard is the default startup mode, that is, standard mode. Every time an Activity is started, a new instance is created.

singleTop

When the target Activity to be started is already on the top of the stack, no new instance will be created, the Activity on the top of the stack will be reused, and its onNewIntent() method will be called; if the target Activity is not on the top of the stack, a new instance will be created just like standard
. instance.

singleTask

In the same task stack, if the target Activity to be started is already in the stack , the Activity will be reused and its onNewIntent() method will be called, and the Activity y above the Activity
will be cleared ; if it is not in the stack, then Create new instance.

singleInstance

Global reuse, no matter which Task stack, as long as the target Activity exists, it will be reused. Each Activity occupies a new Task stack.

Fragment

  • Fragment has its own life cycle
  • Fragment depends on Activity
  • Fragmenti can get the Activity it is in through getActivity(); Activityi can get the Fragment through findFragmentById() or findFragmentByTag() of FragmentManager
  • Fragment and Activity have a many-to-many relationship

fragment.java should be added inside the control targeting framelayout

Common attribute methods

getActivity() gets the Activity where it is located

onAttach() sets the fragment to be tied to the activity where it is located

onDetach sets fragment

Steps for usage

  1. Create fragment custom .java file, inherit from fragment, create corresponding xml file, and carry out fragment fragment design

  2. Override two methods, such as

    public class BFragment extends Fragment {
          
          
    
        private TextView mTvTitle;
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
          
          
            View view = inflater.inflate(R.layout.fragment_b,container,false);
            return view;
        }
    
        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
          
          
            super.onViewCreated(view, savedInstanceState);
            //
            mTvTitle = (TextView) view.findViewById(R.id.tv_title);//之后可以对textview进行操作
        }
    
    }
    
  3. Declare a fragment in the Activity you want to use, then point to an instance of this custom fragment custom.java, and add the fragment to the Activity

    public class ContainerActivity extends AppCompatActivity implements AFragment.IOnMessageClick{
          
          
    
        private AFragment aFragment;
        private TextView mTvTitle;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          
          
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_container);
            mTvTitle = (TextView) findViewById(R.id.tv_title);
    
            //实例化AFragment
            aFragment = AFragment.newInstance("我是参数");
            //把AFragment添加到Activity中,记得调用commit
            getFragmentManager().beginTransaction().add(R.id.fl_container,aFragment,"a").commitAllowingStateLoss();
        }
    
        public void setData(String text){
          
          
            mTvTitle.setText(text);
        }
    
        @Override
        public void onClick(String text) {
          
          
            mTvTitle.setText(text);
        }
    }
    

How to replace a positional afragment with a bfragment

If you implement fragment conversion through click events, you need to create a new bfragment in the onClick method, and thengetFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).commitAllowingStateLoss();

Insert image description here

The problem that getActivity() in Fragment may be null

  1. A less recommended method is to declare an Activity in the fragment, and by overriding the onAttach() method, specify this Activity in the method, and use this declared Activity instead where the getActivity() method is encountered.

    private Activity mActivity;
    @Override
    public void onAttach(Context context){
          
          
    	super.onAttach(context);
    	mActivity=(Activity) context;
    }
    
  2. This method is because onDestory() will be called when the fragment is recycled. At this time, the asynchronous task is canceled in the onDestory() method to avoid the situation where getActivity() is null.

Pass parameters to Fragment

  1. Passing parameters: Create a static method in Afragment. This static method can ensure that the returned Afragment has the same parameters as the original Fragment, avoiding the Fragment being reset due to setting parameters. Then, when obtaining the Afragment that can transmit parameters, call the class method newInstance() method and return a Fragment.

        
    public static AFragment newInstance(String title){
          
          
            AFragment fragment = new AFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title",title);
            fragment.setArguments(bundle);
            return fragment;
        }
    
    private AFragment aFragment=AFragment.newInstance("我是参数");
    
  2. Receive parameters:

    @Override
    public void onViewCreated(Viewview,@Nullable Bundle savedInstancestate){
          
          
    	super.onViewCreated(view,savedInstancestate);
    	//
    	mTvTitle (Textview)view.findviewById(R.id.tv_title);
    	if(getArguments()!null){
          
          
    	mTvTitle.setText(getArguments().getstring("title"));
        }
    }
    

Fragment back stack

getFragmentManager().beginTransaction().replace(R.id.fL_container,bFragment).addToVackStack(null).commitAllowingstateLoss(); //添加到回退栈,在replace生效之后,按返回键会返回到replace之前的Activity,而不是回到mainactivity

When you return to Afragment at this time, the instance is still the same instance, but onCreatView is called again and the view is reconstructed. But we hope that our changes to the original Fragment will not be reset when we return.

At this time, you need to hide the previous composition and then add a new view.

mBtnChange.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                if(bFragment == null){
    
    
                    bFragment = new BFragment();
                }
                Fragment fragment = getFragmentManager().findFragmentByTag("a");
                if(fragment != null){
    
    
                   						 getFragmentManager().beginTransaction().hide(fragment).add(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();//若存在目标fragment,先hide,再add
                }else{
    
    
                    getFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();//如果存在Fragment,直接replace会重置fragment视图,这是不符合预期的
                }
            }
        });

Communication between Fragment and Activity

Fragment sets the control properties in Activity:

Method 1 (not recommended): Declare a method in the Activity. This method can set the properties of the controls in the Activity. Calling the method in the fragment can change the properties in the Activity.

Method two:

  1. Declare an IOnMessageClick interface in Fragment. There is an abstract method in the interface and pass in a formal parameter.
  2. Let Activity must implement this interface in this Fragment and implement abstract methods
  3. In the onAttach method in the Fragment, assign the value of the declared IOnMessageClick interface to the formal parameter context of onAttach.

in AFragment

private IOnMessageClick listener;
public interface IOnMessageClick{
    
    
        void onClick(String text);
    }
    @Override
    public void onAttach(Context context) {
    
    
        super.onAttach(context);
        try {
    
    
            listener = (IOnMessageClick) context;
        }catch (ClassCastException e){
    
    
            throw new ClassCastException("Activity 必须实现 IOnMessageClick接口");
        }
    }

  mBtnMessage.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
//                ((ContainerActivity)getActivity()).setData("你好");
                listener.onClick("你好");
            }
        });

Android event handling that must be deeply understood

Listening-based event processing mechanism

Three elements of monitoring

Event Source button

Event onClick

Event Listener onclicklistener

Implement methods to listen for events

  • Implemented through inner classes
  • via anonymous inner class
  • Implemented through the class where the event source is located
  • Implemented through external classes
  • onClick in layout file (for click event)
    Insert image description here

Method 5: onClick in the layout file (for click events)

Declare the onClick attribute in the control. The value of the attribute can be customized, but there must be a method in the Activity with the same value as this attribute.

For example, when the value is show,

public void show(View v){
    
    
	switch (v.getId()){
    
    
		case R.id.btn_event:
			ToastUtil.showMsg(EventActivity.this,"click...");
			break;
    }
}

What happens if you add multiple listeners of the same type to the same event source?

The system will respond to the last set listener, and the previously set listener will be invalid.

The listener set by onClick in the layout file is considered to be the first listener set.

Callback-based event handling mechanism (jump)

What is the difference between callback mechanism and monitoring mechanism?

The event source and event listener of the callback mechanism are tied together, and the listening mechanism is three separate.

Callback-based event propagation

Source code analysis, understanding the event distribution of View (jump)

Handler message processing

to schedule messages and runnables to be excuted as some
point in the future to do something in the future?

to enqueue an action to be performed on a different thread
than you own inter-thread communication

Common methods

Constructor: Dandler()

method:

postDelayed (thread, milliseconds) How long to delay

public class HandlerActivity extends AppCompatActivity{
    
    
	private Handler mHandler;
	@override
	protected void onCreate(Bundle savedInstanceState){
    
    
		super.onCreate(savedInstancestate);
		setContentview(R.layout.activity_handler);
		mHandler = new Handler();
		mHandler.postDelayed(new Runnable(){
    
    
			@Override
			public void run(){
    
    
			Intent intent = new Intent(HandlerActivity.this,ButtonActivity.class);
			startActivity(intent);
            }
},3686);
    }
}

handleMessage (Message) Send message

private Handler mHandler;

mHandler = new Handler(){
    
    
	@Override
	public void handleMessage(Message msg){
    
    //接收信息
		super.handleMessage(msg);
		switch (msg.what){
    
    
		case 1:
			ToastUti1.showMsg(HandlerActivity.this,"线程通信成功")break;
		}
    };
    new Thread(){
    
    //发送信息
		@Override
		public void run(){
    
    
			super.run();
			Message  message = new Message();
			message.what=1;
			mHandler.sendMessage(message);
        }
	}.start();
}

data storage

sharedpreference lightweight data storage

xml file, storing key-value pairs

Two keys:

SharedPreferences

SharedPreferences.Editor

private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
mSharedPreferences= getsharedPreferences("data",MODE_PRIVATE);//获取对象的方法,第二个形参为模式,一般选择private,不让别的软件读/写
mEditor = mSharedPreferences.edit();

//点击事件里:存储数据
	mEditor.putString("name",mEtName.getText().toString());
	mEditor.apply();//这一步是储存数据,apply可以异步储存数据,commit同步储存数据,一般用apply
//点击事件里:获取数据
	mTvContent.setText(mSharedPreferences.getString("name",""));//getString()+SharedPreferences文件里的"键",比如存储的name

This file is stored in /data/data//shared_prefs. This file cannot be opened from the system interface by default, but generally we obtain the key value directly from the program.

Android storage concept

Insert image description here

Internal storage refers to the storage that comes with the phone, and external storage refers to the SD card, etc.

Internal storage directory:

/data/data//shared_prefs
/data/data//databases
/data/data//files
/data/data//cache

Get file content through context.getCacheDir() and context.getFileDir()

External storage directory:

Public directory (sd card):
Environment.getExternalStoragePublicDirectory(int type)
Private directory:
/mnt/sdcard/Android/data/data//cache
/mnt/sdcard/Android/data/data//files

File internal storage (built-in storage in Android system)

is overwritten storage

Customize two methods save() and read() to store and read data, and then call the two methods in onClick to implement storage and reading.

Store data save()

//存储数据
private void save(String content){
    
    
	Fileoutputstream fileOutputstream null;
	try{
    
    
		fileOutputstream 		openFileOutput(mFileName,MODE_PRIVATE);
		fileoutputstream.write(content.getBytes());
	}
	catch (IOException e){
    
    
		e.printstackTrace();
    }
	finally{
    
    
		if(fileoutputstream !null){
    
    
			try{
    
    
				fileoutputstream.close();
            }
        } catch (IOException e){
    
    
			e.printstackTrace();
        }
    }
}

Read data read()

//读取数据
private String read(){
    
    
	FileInputstream fileInputstream = null;
	try{
    
    
		fileInputstream openFileInput(mFileName);
		byte[]buff new byte[1024];
		StringBuilder sb new StringBuilder("");
		int len =0;
		while ((len fileInputstream.read(buff))>e){
    
    
			sb.append(new String(buff,0,len));
			}
	return sb.toString();
	} catch (IOException e){
    
    
		e.printstackTrace();
	} finally{
    
    
		if(fileInputstream !null){
    
    
			try{
    
    
				fileInputstream.close();
			} catch (IOException e){
    
    
				e.printstackTrace();
			}
		}
    }
	return null;
}

Method application

mBtnSave.setonclickListener(new View.OnclickListener(){
    
    
	@override
	public void onclick(View v){
    
    
		save(mEtName.getText().toString());
	});
mBtnShow.setonclickListener(new View.OnclickListener(){
    
    
	@override
	public void onclick(View v){
    
    
		mTvContent.setText(read());
	});

File external storage (read and write to sd card)

is overwritten storage

The method is similar to internal storage. Storing to the public directory of the SD card requires permission. The method is to write in AndroidManifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    //还有一种,加不加都行
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    

You also need to write: in oncreate() in mainactivity to obtain storage permissions

ActivityCompat.requestPermissions(this,new String[]{
    
    Manifest.permission.WRITE_EXTERNAL_STORAGE},1);

save()

//存储数据
private void save(String content){
    
    
	FileOutputstream fileOutputstream null;
	try{
    
    
//leoutputstream openFiLeoutput(mFtLeName,MODE_PRIVATE);
	File dir=new File(Environment.getExternalFilesDir(null),"skypan");//文件会保存在android/data/appID/file下面
	if(!dir.exists()){
    
    //如果目录不存在就new一个
		dir.mkdirs();
    }
	File file = new File(dir,mFileName);//查找一个文件,第二个参数是文件名
	if(!file.exist()){
    
    //如果不存在,创建一个
		file.createNewFile();
	}
	fileOutputstream new=FileOutputstream(file);
	fileOutputStream.write(content.getBytes());
    }catch (IOException e){
    
    
	e.printstackTrace();
	finally{
    
    	
		if(fileOutputStream !null){
    
    
            try{
    
    
				fileOutputstream.close();
            }
        }catch (IOException e){
    
    
			e.printstackTrace();
        }
    }
    }
}

read()

//读取数据
private String read(){
    
    
	FileInputstream fileInputstream = null;
	try{
    
    
		//fileInputstream = openFileInput(mFileName);
        File file new= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"skypan",mFiname);//file.separator是斜杠/
        fileInputstream= new FileInputStream(file);
		byte[]buff new byte[1024];
		StringBuilder sb new StringBuilder("");
		int len =0;
		while ((len fileInputstream.read(buff))>e){
    
    
			sb.append(new String(buff,0,len));
			}
	return sb.toString();
	} catch (IOException e){
    
    
		e.printstackTrace();
	} finally{
    
    
		if(fileInputstream !null){
    
    
			try{
    
    
				fileInputstream.close();
			} catch (IOException e){
    
    
				e.printstackTrace();
			}
		}
    }
	return null;
}

broadcast

LocalBroadcastManager()

It will only be propagated in the application and will not be propagated in the system.

Use broadcast to realize communication between two activities

However, in the following example, startActivityForResult() is generally used ; you can call back a value after clicking on a page, as mentioned before

Example

  1. Customize a MyBroadcast class and inherit from BroadcastReveiver
  2. Receive broadcast: Rewrite receive, pass in two parameters (context, intent), determine what the action of the Intent is, and then determine what to do through the action
  3. Send a broadcast: Instantiate a MyBroadcast where needed, then instantiate an intentfilter, call intentfilter.addAction("action name"), then register the broadcast, call LocalBroadcastManager's getInstance(this).registerReceiver(MyBroadcast object, intentfilter object )

Custom class to receive broadcast:

private class MyBroadcast extends BroadcastReceiver{
    
    
	@Override
	public void onReceive(Contextcontext,Intent intent){
    
    
		switch (intent.getAction()){
    
    
			case "com.skypan.update":
				mTVTest.setText("123");
				break;	
        }
    }
}

Specific applications:

mBroadcast new = MyBroadcast();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.skypan.update");//添加要做哪些动作
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcast,intentFilter);//注册一个广播

Finally, when closing the Activity, you need to turn off the broadcast in the onDestory method.

@Override
protected void onDestroy(){
    
    
	super.onDestroy();
	LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcast);
}

Property animation

About tweened animation and property animation

Tweening animation only allows you to see some animation, but its properties have not changed, and the xy axis of printing it will still be at the original position. Property animation means that properties change, resulting in some animations

Two commonly used attribute animations:

ValueAnimator

step:

  1. Declare the control, specify the control

  2. Call the animate() method of the control, and then call various animation effects

  3. Offset effect:

    tvText.anmate().translationYBy(500).setDutation(2000).start();//translationYBy延y轴偏移500,setDutation设置动作执行的时间(ms),start执行效果
    
  4. Gradient effect:

    tvTest.animate().alpha(0).setDuration(2000).start();//两秒内亮度渐变为0
    
  5. Other implementation methods:

    1. VaLueAnimator vaLueAnimator = VaLueAnimator.ofInt(0,100);//让数值从0变到100
      vaLueAnimator.setDuration(2000);//设置变化时间
      vaLueAnimator.addUpdateListener(new VaLueAnimator.AnimatorUpdateListener(){
              
              //设置监听器,监听数值变化
      @override
      public void onAnimationUpdate(ValueAnimator animation){
              
              
      	//vaLueAnimator实际的值
      	Log.d("aaaa",animation.getAnimatedvalue()+"");//在控制台打印信息
      	//动画的进度0-1
      	Log.d("aaaa",animation.getAnimatedFraction()+"");
      });
      vaLueAnimator.start();//开启监听器
      

ObjectAnimator.ofFloat()

Available operations: translationX / tanslationY / alpha / rotation / rotationX…

Instructions

ObjectAnimator objectAnimator = ObjectAnimator.ofFLoat(tvTest,"translationY",0,500);//让tvTest进行translationY操作,从0偏移到500,后边也可以传更多数值参数表示从0到500再到其他地方
objectAnimator.setDuration(2000);//设置动画时间
objectAnimator.start();//开启动画
//也可以设置update监听器监视具体信息

Guess you like

Origin blog.csdn.net/m0_63323097/article/details/124511567