Tour of Android

Keywords: Android

Toast is a common pop-up information tool for app s. Here's how to use it.

1. Directly call the makeText() method of Toast class to create. The following code is a common writing method with three parameters,

  • The first one is: context, which is usually passed into this in Activity. You can also get the method of context
  • The second is: the value of string type represents the message you want to pop up
  • The third is: the displayed time. In Toast, there are two optional static constants, Toast.length'short'and Toast.length'long, or you can enter the value of 1000 / 2000 (for 1s/2s)
Toast.makeText(getApplicationContext(),"Pop up message",Toast.LENGTH_SHORT).show();

2. We can also set some other properties, such as display position and font color

public class MainActivity extends AppCompatActivity {

    private Button show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View viewById = findViewById(R.id.show);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                midToast("Hello",2000);
            }
        });
    }

    public void midToast(String text,int showTime){
        Toast toast = Toast.makeText(this,text,showTime);
        toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);  //Set display position
        TextView message = toast.getView().findViewById(android.R.id.message);
        message.setTextColor(Color.YELLOW); //Set font color
        toast.show();
    }

}

Effect

The above gives a button a monitor and a method. In the method, Toast.makeText has a paragraph, and then gravity is set: horizontal or vertical center, and then through toast you can get a view. Through the view you can get a TextView of message, and then you can operate TextView. Finally, remember. show() is displayed.

3. Let's push forward and put a picture

Code

public void midToast(String text,int showTime){
        Toast toast = Toast.makeText(this,text,showTime);
        toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);  //Set display position

        LinearLayout layout = (LinearLayout) toast.getView();   //Strong to LinearLayout
        ImageView imageView = new ImageView(this);    //Defining a picture view requires a context
        imageView.setImageResource(R.mipmap.ic_launcher);       //Set pictures
        layout.addView(imageView);  //Add pictures to it

        TextView message = toast.getView().findViewById(android.R.id.message);
        message.setTextColor(Color.YELLOW); //Set font color
        toast.show();
    }

Effect

 

Posted by danielle on Sat, 23 Nov 2019 12:30:30 -0800