Color Toast In Android
In this tutorial we will show how to build a colored Toast with the help of TextView with an example.
Color Toast:
Color Toast is same as Toast but we will show a message in a colored TextView in a Toast.You can change the color of Toast to which ever you like.
// Toast with Long Period Toast toast = Toast.makeText(getApplicationContext(), "Your Message Here", Toast.LENGTH_LONG); TextView textView = (TextView) toast.getView().findViewById(android.R.id.message); textView.setTextColor(Color.RED); toast.show(); // Toast with Short Period Toast toast = Toast.makeText(getApplicationContext(), "Your Message Here", Toast.LENGTH_SHORT); TextView textView = (TextView) toast.getView().findViewById(android.R.id.message); textView.setTextColor(Color.YELLOW); toast.show();
Now we will show a Toast on Click of a Button in Android Studio.
Example:
File: activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.hss_24.toast.MainActivity"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click Me " android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginTop="158dp" /> </RelativeLayout>
File: MainActivity.java:
import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast toast = Toast.makeText(getApplicationContext(),"You Clicked A Button", Toast.LENGTH_LONG); TextView textView = (TextView) toast.getView().findViewById(android.R.id.message); textView.setTextColor(Color.RED); toast.show(); } }); } }Output:
Comments
Post a Comment