动态定义toast

s

下面分别采用两种方式创建Toast(转:http://zhoujianghai.iteye.com/blog/814940)

/**
 *自定义美化Toast,使用图片作背景
 */
    private void showToast() {
    	Toast t = new Toast(this);
	t.setDuration(Toast.LENGTH_SHORT);
	LinearLayout layout = new LinearLayout(this);
	layout.setBackgroundResource(R.drawable.toast_bg);
	TextView textView = new TextView(this);
	textView.setText("javaeye:您好!");
	textView.setTextSize(14);
	textView.setTextColor(Color.WHITE);
	layout.addView(textView);
	t.setView(layout);
	t.setGravity(Gravity.TOP, 100+20, 200 + 20);
	t.show();
    }
 
    /**
     * 默认的Toast效果
     */
    private void showToast2() {
    	Toast t = Toast.makeText(this, "csdn:您好!", Toast.LENGTH_SHORT);
	t.setGravity(Gravity.TOP, 100+20, 200 + 20);
	t.show();
    }

===================

通过json动态创建 toast

如下所示:

可以通过testCreateJsonObj()创建测试json,也可以直接通过json字符串创建。


Toast toast = Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG);
//View textView = toast.getView();

LinearLayout lay = new LinearLayout(MainActivity.this);
lay.setBackgroundResource(R.drawable.toast_bg);  
lay.setOrientation(LinearLayout.VERTICAL);
//add img
ImageView view = new ImageView(MainActivity.this);
view.setImageResource(R.drawable.ic_launcher);
lay.addView(view);
 				
//JSONObject data = testCreateJsonObj();
JSONObject data = null;
try {
	data = new JSONObject("{\"array\":[{\"color\":\"#ffff0000\",\"text\":\"andytest1\",\"size\":\"24\",\"gravity\":\"center\"},{\"color\":\"#ff0000ff\",\"text\":\"andytest2\n换行测试\",\"size\":\"14\",\"gravity\":\"left\"}],\"layout\":{\"gravity\":\"center\"}}");
} catch (JSONException e1) {
	e1.printStackTrace();
}
Log.e("andy_show_json:", data.toString());
int pos = Gravity.CENTER;
try {
	pos = str2pos(data.getJSONObject("layout").getString("gravity"));

	JSONArray array = data.getJSONArray("array");
	for (int i = 0; i < array.length(); i++) {
		JSONObject iObj = array.getJSONObject(i);
		addTextView(lay, iObj);
	}
} catch (JSONException e) {// 抛错 说明JSON字符不是数组或根本就不是JSON
	e.printStackTrace();
}

toast.setGravity(pos, 0, 0);
toast.setView(lay);
toast.show();
相关函数:

public JSONObject createJsonObject(HashMap<String, String> hashMap) {
	JSONObject jsonobj = new JSONObject();
	Set<String> keys = hashMap.keySet();
	try {
		for (Iterator<String> iterator = keys.iterator(); iterator
				.hasNext();) {
			String key = iterator.next();
			jsonobj.put(key, hashMap.get(key));
		}
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return jsonobj;
}

public JSONArray createJsonArray(ArrayList<HashMap<String, String>> mylist) {
	JSONArray array = new JSONArray();
	for (Iterator<HashMap<String, String>> iterator = mylist.iterator(); iterator
			.hasNext();) {
		JSONObject jsonobj = createJsonObject(iterator.next());
		array.put(jsonobj);
	}
	return array;
}

public JSONObject testCreateJsonObj(){
	JSONObject jsonobj=new JSONObject();
	try {
		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("text", "andytest1");
		map.put("size", "24");
		map.put("color", "#ffff0000");
		map.put("gravity", "center");
		mylist.add(map);
		
		map = new HashMap<String, String>();
		map.put("text", "andytest2\n换行测试");
		map.put("size", "14");
		map.put("color", "#ff0000ff");
		map.put("gravity", "left");
		mylist.add(map);
		
		map = new HashMap<String, String>();
		map.put("gravity", "center");
		jsonobj.put("layout", createJsonObject(map));
		jsonobj.put("array", createJsonArray(mylist));
	} catch (JSONException e) {
		e.printStackTrace();
	}
	
	
	return jsonobj;
}
private int str2pos(String str) {
	int pos = Gravity.CENTER;
	if(str.equals("right")) {
		pos = Gravity.RIGHT;
	} else if(str.equals("left")){
		pos = Gravity.LEFT;
	} else {//center
		pos = Gravity.CENTER;
	}
	return pos;
}

private int color2int(String color) {
	// 服务器端下发color格式:#ffcc00cc 或 #ffcc00
	int value = 0xff000000;
	if (color != null && color.startsWith("#")
			&& (color.length() == 7 || color.length() == 9)) {
		try {
			value = Color.parseColor(color);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return value;
}
private void addTextView(LinearLayout lay, JSONObject iObj) {
	TextView textView = new TextView(MainActivity.this);
	try {
		textView.setText((String)iObj.get("text"));
    	textView.setTextSize(Integer.valueOf((String)iObj.get("size")));  
        textView.setTextColor(color2int((String)iObj.get("color")));
        textView.setGravity(str2pos((String)iObj.get("gravity")));
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	
	lay.addView(textView, p);
}






s





s




### 实现 Toast 组件的全局定义 #### Vue 中实现 Toast 的全局注册 为了使 `Toast` 组件可以在整个 Vue 应用程序中使用,在项目的入口文件 `main.js` 或者相应的配置文件里进行如下操作: ```javascript // main.js import Vue from 'vue'; import App from './App.vue'; // 引入自定义 toast 资源 import './assets/css/toast.css'; // 自定义样式表 import Toast from './assets/js/toast'; // 导入 toast 功能逻辑模块 Vue.use(Toast); new Vue({ render: h => h(App), }).$mount('#app'); ``` 通过上述方式,实现了对 `Toast` 插件的安装并将其设置为全局可用[^1]。 对于 React 来说,则可以通过创建高阶组件(HOC)或利用 Context API 将 `Toast` 提供给应用中的任何地方。下面展示一种基于 HOC 和 context 的解决方案: #### React 中实现 Toast 的全局管理 首先构建一个上下文环境来存储通知消息队列以及相关的方法: ```jsx // src/context/ToastContext.jsx import { createContext, useState } from "react"; export const ToastContext = createContext(); const ToastProvider = ({ children }) => { const [notices, setNotices] = useState([]); function addNotice(message, type="info") { let id = Date.now(); setNotices(prev Notices => [...prevNotices, {id, message, type}]); setTimeout(() => removeNotice(id), 3000); } function removeNotice(id){ setNotices(notices.filter(item=>item.id !== id)); } return ( <ToastContext.Provider value={{ notices, addNotice }}> {children} </ToastContext.Provider> ); }; export default ToastProvider; ``` 接着编写具体的 `Toast` 显示逻辑: ```jsx // src/components/Toast.jsx import React, { useContext } from "react"; import "./Toast.scss"; // 加载 CSS 文件 import { ToastContext } from "../context/ToastContext"; function Toast() { const { notices } = useContext(ToastContext); return ( <> {notices.map(({ id, message, type }, index) => ( <div key={index} className={`toast ${type}`}> {message} </div> ))} </> ); } export default Toast; ``` 最后一步是在根级组件包裹一层 Provider 并挂载 Toast 组件以便于在整个应用程序范围内监听变化: ```jsx // src/index.jsx or App.jsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import ToastProvider from "./context/ToastProvider"; import Toast from "./components/Toast"; const rootElement = document.getElementById("root"); const root = ReactDOM.createRoot(rootElement); root.render( <React.StrictMode> <ToastProvider> <App /> <Toast /> {/* 渲染 Toast */} </ToastProvider> </React.StrictMode> ); ``` 这样就完成了在 React 项目内的全局 Toast 定义[^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值