In Android,Toast is a notification message that usees to displays a message to the user and message will disappear automatically after a certain period of time.
Information can be simple text, it can be complex pictures and other content (shows a view) .
main.xml:
Add Layout for Toast my_toast.xml:
ToastActivity.java:
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Toast View" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=" Custom Toast View" /> </LinearLayout>
Add Layout for Toast my_toast.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toast_border_one" > <ImageView android:src="@drawable/warning" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:id="@+id/TextViewInfo" android:layout_height="wrap_content" android:text="Your error message here" android:layout_gravity="center_vertical" > </TextView> </LinearLayout>
ToastActivity.java:
public class ToastActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnone=(Button)findViewById(R.id.button1); btnone.setOnClickListener(btnoneListner); Button btntwo=(Button)findViewById(R.id.button2); btntwo.setOnClickListener(btntwoListner); } OnClickListener btnoneListner=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(ToastActivity.this,"Your Text Here",Toast.LENGTH_LONG).show(); } }; OnClickListener btntwoListner=new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub showToast(); } }; public void showToast() { View toastRoot = getLayoutInflater() .inflate(R.layout.my_toast, null); Toast toast=new Toast(getApplicationContext()); toast.setView(toastRoot); toast.setGravity(Gravity.CENTER, 0, 40); toast.setDuration(Toast.LENGTH_LONG); TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo); tv.setText("Your error message here"); toast.show(); } }
Download Source Code: CustomToast
0 comments:
Post a Comment