Create Project
Create new project in Android Studio with steps as below:
Step 1: Input Project Name and Select Project Location
Step 2: Select SDK for Android App
Step 3: Select Default Activity for App
Step 4: Finish create project
Add Strings
Open res\values\strings.xml file and add new string as below:
<resources>
<string name="app_name">Learn Android with Real Apps</string>
<string name="show_custom_toast">Show Custom Toast</string>
<string name="this_is_custom_toast">This is custom toast</string>
</resources>
Toast ICon
Copy images make toast icon to res\drawable folder.
Toast Background Color
Create new xml file named toast_background_color.xml in res\drawable folder as below:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#E41B17" />
<corners android:radius="5dp" />
</shape>
Main Activity Layout
Open res\layout\activity_main.xml file and create layout as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/buttonCustomToast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/show_custom_toast" />
</LinearLayout>
Main Activity Class
Add code to MainActivity.java in android.demo.learnandroidwithrealapps package as below:
package android.demo.learnandroidwithrealapps;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button buttonCustomToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
buttonCustomToast = findViewById(R.id.buttonCustomToast);
buttonCustomToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonCustomToast_onClick(view);
}
});
}
private void buttonCustomToast_onClick(View view) {
View toastLayout = getLayoutInflater().inflate(R.layout.custom_toast_layout, null);
TextView textViewMessage = toastLayout.findViewById(R.id.textViewMessage);
textViewMessage.setText(getText(R.string.this_is_custom_toast));
Toast toast = new Toast(getApplicationContext());
toast.setView(toastLayout);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
}
Structure of Project
Run App
Load Main Activity
Show Custom Toast When Click Button