The first line of code, Chapter 2

Time:2020-11-28

Summary of Chapter 2 of the first line of code

The summary of the last chapter is written after reading it. I feel that there are a lot of omissions. From this chapter, I summarize while reading.

Because of the new things, the summary of the first line of code will stop for a while, but not for long.


Create activities manually

  • Select add no activity to create an activity.
  • Create the layout folder under res, and create first under the folder_ Layout.
  • Add a button to the layout.
  • Loads the layout in the activity.
  • Register in the androidmanifest file.
  • Configure the main activity in androidmanifest, andInternal join。

Use toast() in an activity:

  • Add in oncreat().

    Button button1 = (Button) findViewById(R.id.button_1);
    button1.setOnClickListener(new  View.OnClickListener () {// register listener
        public void onClick(View v){
            Toast.makeText(MainActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
        }
    
    });
  • The layout elements are obtained through the findviewbyid() method, and the view object (button) is converted into a button object.

  • Register the listener for the button.

    • makeText(context object, text content, duration). Show(). The duration is as follows: Toast.LENGTH_ Short and Toast.LENGTH_ LONG

    PS: set up automatic packet guiding here

    The first line of code, Chapter 2

@+ID / xxx defines an ID in XML

@ID / xxx introduces an ID in XML


Using menu in an activity:

  • Create menu folder under res, create main, createLabel to create a menu item.

  • Add oncreationsmenu() to the activity and use getmenuinflater(). Inflate (R menu.main The first parameter is the resource file to create the menu, and the second parameter is the menu object to which the menu item is added.

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
  • Define the menu response event, and override onoptionsiteselected() in the activity by calling item.getItemId () to determine which menu item we click on.

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.app_item:
                Toast.makeText(this,"You clicked Add",Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(this,"You clicked Remove",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return  true;
    }

The first line of code, Chapter 2 The first line of code, Chapter 2 The first line of code, Chapter 2


Destroy an activity:

  • Modify the code in the button listener (I commented out the previous code)

    button1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            //Toast.makeText(MainActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
            finish();
        }
    
    });

Intent

Using explicit intent

PS: intent is an important way of interaction between components in Android program.

  • Create a second activity

  • Modify the click event of the button in the first activity (same note)

    button1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            //Toast.makeText(MainActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
            //finish();
            Intent intent = new Intent(MainActivity.this,SecondActivity.class);
            startActivity(intent);
        }
    
    });
  • Construct intent first and pass in MainActivity.this As context, pass in SecondActivity.class As a target activity.

  • Execute intent through the startactivity() method.

  • Press the back key to destroy the current activity and return to the previous activity.
    The first line of code, Chapter 2


Use implicit intent

  • stayConfiguration under labelContent of

  • Modify the click event of button in mainactivity

    button1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            //Toast.makeText(MainActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
            //finish();
            //Intent intent = new Intent(MainActivity.this,SecondActivity.class);
            //startActivity(intent);
            Intent intent = new Intent("com.example.androidtest.ACTION_START");
            startActivity(intent);
        }
    
    });
  • The tag declares that the current activity can respond com.example.androidtest .ACTION_ Start this activity,The tag contains some additional information to more precisely indicate the category that may be included in the intent that the current activity can respond to.onlyAndOnly when the action and category specified in intent are matched, can the activity respond to intent.

  • android.intent.category . default is a default category, which is automatically added to the intent when the startactivity method is called.


More implicit intents

  • Modify the main activity to

    button1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Intent intent = new Intent( Intent.ACTION_ View); // specifies that the action of intent is Intent.ACTION_ View, built-in action for Android
          
       intent.setData(Uri.parse("http://www.baidu.com"));
            Startactivity (intent); // passed Uri.parse () method to parse the URL string into URI object, and then call setdata() method to pass this URI object.
  • Setdata() accepts a URI object that specifies the data currently being operated on by intent.


Connect

  • The first line of code, Chapter 2
  • Create activities thirdactivity and third_ layout

  • In AndroidManifest.xml Registered in

  • Configure

  • tools:ignore= “Applinkurlerror” is added by prompt!


Passing data to the next activity

  • Modify the main activity:

    public void onClick(View v){
        String data = "Hello SecondActivity";
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtra ("extra_ Data ", data); // takes two parameters, the first is the key
        startActivity(intent);
    }
  • Modify secondactivity:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);
        Intent intent = getintent(); // get the intent used to start secondactivity
        String data = intent.getStringExtra("extra_data");
        Log.d("SecondActivity",data);
    }

Returns data to the previous activity

  • Write in main activity:

    public void onClick(View v){
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        Startactivityforresult (intent, 1); // returns a result to the previous activity when the activity is destroyed. The second parameter is the request code, which is used to determine the source of the data in subsequent callbacks.
    }
  • SecondActivity:

    button2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){Intent intent = new Intent();
            intent.putExtra ("data_ Return "," Hello main activity ");
            setResult(RESULT_ OK, intent); // important! Dedicated to the data returned by the previous activity. The first parameter is used to return the processing result to the previous activity, usually only result is used_ OK or result_ For the two values of cancel, the second parameter passes the intent with data back.
            Finish();} // destroy activity
    });
    • Main activity override onactivityresult(): callback method
    Protected void onactivityresult (int requestcode, int resultcode, intent data) {// the first parameter is the request code 1 passed in by the activity, and the second parameter is the processing result result passed in when data is returned_ OK。
        super.onActivityResult (requestcode, resultcode, data); // Note
        switch (requestCode) {
            case 1:
                if (requestCode == RESULT_OK) {
                    String returnedData = data.getStringExtra("data_return");
                    Log.d("MainActivity", returnedData);
                }
                break;
            default:
        }
    }

Back

  • On the basis of the above, rewrite in secondactivity:

    public void onBackPressedf(){
        Intent intent = new Intent();
        intent.putExtra ("data_ Return "," Hello main activity ");
        setResult(RESULT_OK,intent);
        finish();
    }

Activity cycle

  • Each activity may have up to four states in its life cycle.
    • Running body
    • Pause state
    • Stop state
    • Destroy State

The first line of code, Chapter 2

Experience the life cycle of activities

  • Create a new project, create the main activity, two sub activities (normalactivity, dialogactivity) and the corresponding layout. A textview is added to each of the two sub activity layouts, and two buttons are added to the main activity layout.

  • modify AndroidManifest.xml :

  • Modify main activity Code:

    Expand to view
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startNormalActivity = (Button) findViewById(R.id.start_normal_activity);
        Button startDialogActivity = (Button) findViewById(R.id.start_dialog_activity);
        startNormalActivity.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(MainActivity.this,NormalActivity.class);
                startActivity(intent);
            }
        });
        startDialogActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,DialogActivity.class);
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart");
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestory");
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

Start mode of the activity

standard

  • Standard is the default startup mode for the activity.
  • An activity that uses standard mode creates a new instance of the activity each time it is started.

singelTop

  • When starting an activity, if it is found that the top of the returned stack is already the activity, it is considered that it can be used directly instead of creating a new activity instance.

  • modify AndroidManifest.xml :

    Add in activity tagandroid:launchMode="singleTop"

singelTask

  • Each time an activity is started, the system first checks whether there is an instance of the activity in the return stack. If it is found that it already exists, it will directly use the instance, and all activities above the activity will be taken out of the stack. If it is found that there is no instance, a new activity instance will be created.

singleInstance*

  • Activities specified as singleinstance mode enable a new return stack to manage the activity

Know the skills of the current activity

  • Create a new class (Java class): no registration required

    Public class baseactivity extends appcompatactivity {// inherits appcompatactivity!
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d("BaseActivity",getClass().getSimpleName());
        }
    }
  • Let all classes inheritBaseActivity

Problems

  • This error message appears every time it runs E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
    …… E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
  • Follow the example to add to the implicit intent activity intent.addCategory (…… )Did not report an error according to the book, but the program stopped running.
  • In the experiment at, clicking the button of the second dialogue did not respond, and the program did not report an error. Neither method on the Internet worked.