下面列出了怎么用android.widget.Toast的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMediaLoader();
initListView();
findViewById(R.id.cleanCache).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
DownloadManager.getInstance(MainActivity.this).cleanCacheDir();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Error clean cache", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (fam.isOpened()) {
fam.close(true);
} else if (mBackHandedFragment == null || !(mBackHandedFragment instanceof WebViewFragment)) {
switchContent(WebViewFragment.getInstance());
} else if (!mBackHandedFragment.onBackPressed()) {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
@Override
public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
if (poiDetailSearchResult.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(mContext, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
} else {
List<PoiDetailInfo> poiDetailInfoList = poiDetailSearchResult.getPoiDetailInfoList();
if (null == poiDetailInfoList || poiDetailInfoList.isEmpty()) {
Toast.makeText(mContext, "抱歉,检索结果为空", Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < poiDetailInfoList.size(); i++) {
PoiDetailInfo poiDetailInfo = poiDetailInfoList.get(i);
if (null != poiDetailInfo) {
Toast.makeText(mContext,
poiDetailInfo.getName() + ": " + poiDetailInfo.getAddress(),
Toast.LENGTH_SHORT).show();
}
}
}
}
public static void requestCameraPermission(Activity activity, boolean requestWritePermission) {
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.CAMERA) || (requestWritePermission &&
ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE));
if (showRationale) {
Toast.makeText(activity,
"Camera permission is needed to run this application", Toast.LENGTH_LONG).show();
} else {
// No explanation needed, we can request the permission.
String permissions[] = requestWritePermission ? new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE}: new String[]{Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(activity,permissions,RC_PERMISSION_REQUEST);
}
}
/**
* 设置分享回调
*
* @param
*/
public static void registerCallback(final Context context) {
mController.getConfig().cleanListeners();
mController.getConfig().registerListener(new SnsPostListener() {
@Override
public void onStart() {
}
@Override
public void onComplete(SHARE_MEDIA platform, int stCode,
SocializeEntity entity) {
if (stCode == 200) {
Toast.makeText(context, "分享成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "分享失败", Toast.LENGTH_SHORT).show();
}
}
});
}
public void deleteMultiReddit(MultiReddit multiReddit) {
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.delete)
.setMessage(R.string.delete_multi_reddit_dialog_message)
.setPositiveButton(R.string.delete, (dialogInterface, i)
-> DeleteMultiReddit.deleteMultiReddit(mOauthRetrofit, mRedditDataRoomDatabase,
mAccessToken, mAccountName, multiReddit.getPath(), new DeleteMultiReddit.DeleteMultiRedditListener() {
@Override
public void success() {
Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show();
loadMultiReddits();
}
@Override
public void failed() {
Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_failed, Toast.LENGTH_SHORT).show();
}
}))
.setNegativeButton(R.string.cancel, null)
.show();
}
public static @CheckResult
Toast snackBar(Context context, CharSequence message_to_show, boolean duration) {
@SuppressLint("InflateParams")
View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_snackbar, null);
AppCompatTextView message = view.findViewById(R.id.message);
message.setText(message_to_show);
Toast toast = new Toast(context);
toast.setView(view);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
if (duration) {
toast.setDuration(Toast.LENGTH_LONG);
} else {
toast.setDuration(Toast.LENGTH_SHORT);
}
return toast;
}
@Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof GenerateReviewFragment) {
if (((GenerateReviewFragment) f).backOk()) {
super.onBackPressed();
}
} else if (f instanceof NodeFragment) {
if (!((NodeFragment) f).isRefreshing()) {
super.onBackPressed();
} else {
Toast.makeText(LoginActivity.this, getString(R.string.node_refresh_wait), Toast.LENGTH_LONG).show();
}
} else if (f instanceof LoginFragment) {
if (((LoginFragment) f).isFabOpen()) {
((LoginFragment) f).animateFAB();
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_gnr);
Button btnstore = findViewById(R.id.btnstore);
ImageView myImage = findViewById(R.id.imageView1);
Bundle QRData = getIntent().getExtras();//from QRGenerator
qrInputText = QRData.getString("gn");
qrInputType = QRData.getString("type");
Glide.with(this).load(QRGeneratorUtils.createImage(this, qrInputText, qrInputType)).into(myImage);
btnstore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
QRGeneratorUtils.saveCachedImageToExternalStorage(QrGeneratorDisplayActivity.this);
Intent i = new Intent(QrGeneratorDisplayActivity.this, ScannerActivity.class);
startActivity(i);
Toast.makeText(QrGeneratorDisplayActivity.this, "QR code stored in gallery", Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onClick(View v) {
// This condition will satisfy only when it is not an autolinked
// text
// onClick action
boolean isNotLink = layout.recontent.getSelectionStart() == -1 && layout.recontent.getSelectionEnd() == -1;
boolean isDeleted = msg.getRetweeted_status() == null || msg.getRetweeted_status().getUser() == null;
if (isNotLink && !isDeleted) {
startActivity(BrowserWeiboMsgActivity.newIntent(BeeboApplication.getInstance().getAccountBean(),
msg.getRetweeted_status(), BeeboApplication
.getInstance().getAccessTokenHack()));
} else if (isNotLink) {
Toast.makeText(getActivity(), getString(R.string.cant_open_deleted_weibo), Toast.LENGTH_SHORT).show();
}
}
private void setReminder() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getString(R.string.app_name));
progressDialog.setMessage(getString(R.string.wait));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
String name = nameET.getText().toString();
String address = addressET.getText().toString();
String full_date = onDateEt.getText().toString();
if (name.trim().length() > 0 && address.trim().length() > 0 && full_date.trim().length() > 0) {
progressDialog.show();
setReminderNow(name, address, full_date);
} else
Toast.makeText(this, getString(R.string.please_input), Toast.LENGTH_LONG).show();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getWindow().setBackgroundDrawable(null);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, new IntentFilter(MediaChooserConstants.BRAODCAST_VIDEO_RECEIVER));
if (mView == null) {
mView = inflater.inflate(R.layout.view_grid_layout_media_chooser, container, false);
mGridView = (GridView) mView.findViewById(R.id.gridViewFromMediaChooser);
init();
} else {
if (mView.getParent() != null) {
((ViewGroup) mView.getParent()).removeView(mView);
}
if (mBucketAdapter == null || mBucketAdapter.getCount() == 0) {
Toast.makeText(getActivity(), getActivity().getString(R.string.no_media_file_available), Toast.LENGTH_SHORT).show();
}
}
return mView;
}
private void copyText(final String clips) {
mHandler.post(new Runnable() {
@Override
public void run() {
//copy clips to clipboard
ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
cb.setText(clips);
//make toast
String toastClips =clips;
if ( clips.length() > 15) {
toastClips = clips.substring(0, 15) + "…";
}
Toast.makeText(ClipObjectActionBridge.this,
getString(R.string.toast_copied, toastClips+"\n"),
Toast.LENGTH_SHORT
).show();
}
});
}
@Override
protected void onPostExecute(final Pair<Integer, String> result) {
super.onPostExecute(result);
final Context context = contextReference.get();
if (context == null) return;
switch (result.first()) {
case FAILURE:
Toast.makeText(context,
context.getResources().getString(R.string.error),
Toast.LENGTH_LONG).show();
break;
case SUCCESS:
String dir = result.second();
Toast.makeText(context,
dir==null? context.getString(R.string.done) : context.getString(R.string.file_saved_to, dir),
Toast.LENGTH_LONG).show();
break;
case WRITE_ACCESS_FAILURE:
Toast.makeText(context, R.string.error,
Toast.LENGTH_LONG).show();
break;
}
}
public void checkUpdate(boolean showMsg) {
BaseModelImpl.getInstance().getRetrofitString("https://api.github.com")
.create(IHttpGetApi.class)
.get(MApplication.getInstance().getString(R.string.latest_release_api), AnalyzeHeaders.getMap(null))
.flatMap(response -> analyzeLastReleaseApi(response.body()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new MyObserver<UpdateInfoBean>() {
@Override
public void onNext(UpdateInfoBean updateInfo) {
if (updateInfo.getUpDate()) {
} else if (showMsg) {
Toast.makeText(activity, "已是最新版本", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Throwable e) {
if (showMsg) {
Toast.makeText(activity, "检测新版本出错", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String result = "";
switch (item.getItemId()) {
case R.id.ac_toolbar_copy:
result = "Copy";
break;
case R.id.ac_toolbar_cut:
result = "Cut";
break;
case R.id.ac_toolbar_del:
result = "Del";
break;
case R.id.ac_toolbar_edit:
result = "Edit";
break;
case R.id.ac_toolbar_email:
result = "Email";
break;
}
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
if (outFile.exists()) {
adapter.add(outFile);
adapter.notifyDataSetChanged();
saveHistory();
setTexturepack(outFile);
Toast.makeText(ManageTexturepacksActivity.this, R.string.extract_textures_success,
Toast.LENGTH_SHORT).show();
} else {
new AlertDialog.Builder(ManageTexturepacksActivity.this)
.setMessage(
hasSu ? R.string.extract_textures_error
: R.string.extract_textures_no_root)
.setPositiveButton(android.R.string.ok, null).show();
}
}
private static void show(Context context, String text, boolean isLong) {
RxUtils.disposeSafety(sDisposable);
if (sToast != null) {
sToast.setText(text);
} else {
sToast = Toast.makeText(context, text, !isLong ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG);
}
sToast.show();
sDisposable = Observable.timer(!isLong ? SHORT_DELAY : LONG_DELAY, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
sToast.cancel();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Map<String, String> item = (Map<String, String>)l.getItemAtPosition(position);
String className = item.get("class");
if (className != null) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(this, className));
intent.putExtra("name", item.get("name"));
intent.putExtra("data", item.get("data"));
startActivity(intent);
} else {
String result = VSEngine.test();
Toast.makeText(getApplicationContext(), "executing result: " + result, Toast.LENGTH_LONG).show();
}
}
public static AlertDialog getCreateVirtualAlbumDialog(final Context context, final OnCreateVirtualAlbumCallback callback) {
@SuppressLint("InflateParams")
View dialogLayout = LayoutInflater.from(context)
.inflate(R.layout.input_dialog_layout, null, false);
final EditText editText = dialogLayout.findViewById(R.id.edit_text);
Theme theme = Settings.getInstance(context).getThemeInstance(context);
final AlertDialog dialog = new AlertDialog.Builder(context, theme.getDialogThemeRes())
.setTitle(R.string.create_virtual_album)
.setView(dialogLayout)
.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
String name = editText.getText().toString();
ArrayList<VirtualAlbum> virtualAlbums = Provider.getVirtualAlbums(context);
for (int i = 0; i < virtualAlbums.size(); i++) {
if (virtualAlbums.get(i).getName().equals(name)) {
Toast.makeText(context, R.string.virtual_album_different_name, Toast.LENGTH_SHORT).show();
return;
}
}
VirtualAlbum virtualAlbum = new VirtualAlbum(name, new String[]{});
Provider.addVirtualAlbum(context, virtualAlbum);
Provider.saveVirtualAlbums(context);
callback.onVirtualAlbumCreated(virtualAlbum);
String message = context.getString(R.string.virtual_album_created, name);
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, null)
.create();
//noinspection ConstantConditions
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
return dialog;
}
protected void didUnbindDevice(GizWifiErrorCode result, java.lang.String did) {
progressDialog.cancel();
if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {
// String unBoundFailed = (String) getText(R.string.unbound_failed);
Toast.makeText(this, toastError(result), 2000).show();
}
}
private void setLoginResutToView(LoginResult result, String platformName) {
if (null != result) {
mTvResult.setText(platformName + "登录结果:" + result.toString());
} else {
Toast.makeText(ShareDemoActivity.this, platformName + "登录结果为空", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPostExecute(UpdateInfo updateInfo) {
super.onPostExecute(updateInfo);
SharedPreferences.Editor editor = preferences_update.edit();
if (mContext != null && updateInfo != null) {
if (Integer.parseInt(updateInfo.getVersionCode()) > getPackageInfo().versionCode) {
showUpdateUI(updateInfo);
editor.putBoolean("hasNewVersion", true);
editor.putString("latestVersionCode",
updateInfo.getVersionCode());
editor.putString("latestVersionName",
updateInfo.getVersionName());
} else {
if (isHintVersion) {
Toast.makeText(mContext, R.string.was_latest_version, Toast.LENGTH_LONG).show();
}
editor.putBoolean("hasNewVersion", false);
}
} else {
if (isHintVersion) {
Toast.makeText(mContext, R.string.was_latest_version, Toast.LENGTH_LONG).show();
}
}
editor.putString("currentVersionCode", getPackageInfo().versionCode + "");
editor.putString("currentVersionName", getPackageInfo().versionName);
editor.apply();
if (UpdateHelper.this.updateListener != null) {
UpdateHelper.this.updateListener.onFinishCheck(updateInfo);
}
}
public void loadCloud() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");;
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "cloudFile"), 5);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}
}
/**
* 获取BLE的特征值
* @param gattServices
*/
private void getCharacteristic(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid = null;
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
uuid = gattService.getUuid().toString();
//找uuid为0xffe0的服务
if (uuid.equals(C.SERVICE_UUID)) {
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
//找uuid为0xffe1的特征值
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
uuid = gattCharacteristic.getUuid().toString();
if(uuid.equals(C.CHAR_UUID)){
mCharacteristic = gattCharacteristic;
final int charaProp = gattCharacteristic.getProperties();
//开启该特征值的数据的监听
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mBluetoothLeService.setCharacteristicNotification(
mCharacteristic, true);
}
System.out.println("uuid----->" + uuid);
}
}
}
}
//如果没找到指定的特征值,直接返回
if (mCharacteristic == null) {
Toast.makeText(DeviceControlActivity.this, "未找到指定特征值",
Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void sendMessage(final Message message) throws RemoteException {
Log.d("RemoteService", "sendMessage in " + Thread.currentThread().getName());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RemoteService.this, String.valueOf(message.getContent()), Toast.LENGTH_SHORT).show();
}
});
message.setSendSuccess(isConnected);
}
private void showToast(final String message) {
mActivity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
}
});
}
private void initVerticalListView(List<DemoItem> content, ListView listView) {
LayoutInflater appInflater = LayoutInflater.from(getActivity().getApplicationContext());
ListAdapter adapter = new DemoListAdapter(appInflater, content);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"click " + position,Toast.LENGTH_SHORT).show();
}
});
ElasticityHelper.setUpOverScroll(listView);
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Log.d(TAG, "onServiceConnected");
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
if(mBluetoothLeService.isConnected())
mBluetoothLeService.readVidonnCharacteristic(VidonnGattAttributes.VIDONN_PERSONAL_INFO);
else {
Toast.makeText(getApplicationContext(), "Warning! Not connected to a bracelet!", Toast.LENGTH_LONG).show();
}
}
public void onFilePopUpClicked(View v, int position) {
final PopupMenu menu = new PopupMenu(getActivity(), v);
menu.setOnMenuItemClickListener(item -> {
ArrayList<Song> songs = new ArrayList<>();
Collection<File> files = FileUtils.listFiles(new File(fileFolderPathList.get(position)), new String[]{"mp3", "ma4", "ogg", "wav"}, false);
for (File file : files) {
songs.add(getSongs(new String[]{file.getAbsolutePath()}));
}
if (songs.size() == 0) {
Toast.makeText(mContext, R.string.audio_files_not_found, Toast.LENGTH_SHORT).show();
return false;
}
switch (item.getItemId()) {
case R.id.popup_file_play:
mApp.getPlayBackStarter().playSongs(songs, 0);
startActivity(new Intent(mContext, NowPlayingActivity.class));
break;
case R.id.popup_file_add_to_queue:
new AsyncAddTo(getString(R.string.songs_added_to_queue), true, songs).execute();
break;
case R.id.popup_file_play_next:
new AsyncAddTo(getString(R.string.will_be_played_next), false, songs).execute();
break;
}
return false;
});
menu.inflate(R.menu.popup_file);
menu.show();
}