Creating custom toast using xml.....
This article shows you to create custom toast in android.
1- Create xml for Toast(toast.xml).
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="@drawable/image"
>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textSize="20sp"
/>
</LinearLayout>
2- Create Activity Class(MainActivity.java).
import android.app.Activity;import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showCustomToast("Hey! I'm Toast.");
}
});
}
protected void showCustomToast(String msg) {
// TODO Auto-generated method stub
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup) findViewById(R.id.toast_layout_root));
textview = (TextView) layout.findViewById(R.id.text);
textview.setText("" + text);
Toast toast = new Toast(this);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);/* Replace (0,0) to corresponding (x,y) to set position of toast.*/
toast.setView(layout);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
}
0 comments :
Post a Comment