Android Toast自己定义Toast例子

通过自己定义一个layout布局文件,然后在Toast里面设置这个layout为布局view,最后以Toast的方式呈现。

1.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" >
  <TextView android:layout_width="wrap_content" android:id="@+id/message"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical" android:textColor="#ff00ff00"></TextView>
</LinearLayout>

2.activity代码:

public class ListViewActivity extends Activity {
    private ListView listView;
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = new ListView(this);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, getData()));
        setContentView(listView);
        initToast();
                   
        listView.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);
                TextView message = (TextView) toastRoot.findViewById(R.id.message); 
                message.setText("item:" + arg2);
                toast.setView(toastRoot);
                toast.show();
            }
                       
        });
    }
               
    private void initToast()
    {
        View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);
        toast=new Toast(getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 10); 
        toast.setDuration(Toast.LENGTH_LONG);  
        toast.setView(toastRoot);
    }
               
    private List<String> getData(){
        List<String> data = new ArrayList<String>();
        data.add("测试数据1");
        data.add("测试数据2");
        data.add("测试数据3");
        data.add("测试数据4");
        data.add("测试数据5");
        data.add("测试数据6");
        data.add("测试数据7");
        data.add("测试数据8");
        data.add("测试数据9");
        data.add("测试数据10");
        data.add("测试数据11");
        data.add("测试数据12");
        return data;
    }
               
               
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.list_view, menu);
        return true;
    }
}

3.效果图:


你可能感兴趣的:(android,toast)