简体   繁体   English

Android中是否可以使用某种#define来简化语句?

[英]Is there some kind of #define in Android that I can use to simplify a statement?

Consider the java android statement: 考虑一下Java android语句:

Toast.makeText (this, "some message here", Toast.LENGTH_SHORT).show ();

I would like to write something like this: 我想写这样的东西:

myToast ("some message here");

and then, it should be converted/translated/replaced by the the full version of statement. 然后,应使用完整版本的语句对其进行转换/翻译/替换。

I would like to know if Android Studio IDE (mine is 3.4.1) has some kind of helper since there is no pre-processor as in C, and so #define is not an option. 我想知道Android Studio IDE(我的版本是3.4.1)是否具有某种帮助程序,因为没有像C中那样的预处理器,因此#define不是一个选择。

Just define a method: 只需定义一个方法:

static void myToast(Context ctx, String message) {
  Toast.makeText (ctx, message, Toast.LENGTH_SHORT).show ();
}

I know the question is tagged with Java, but since you're talking Android I figure I'll give you a Kotlin solution as well. 我知道问题是用Java标记的,但是既然您使用的是Android,我想我也会为您提供Kotlin解决方案。

Define an extension method on Context : Context上定义扩展方法:

fun Context.myToast(str: String) {
    Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
}

Now you can use this in any Activity (or any other Context ) without having to define it everywhere. 现在,您可以在任何Activity (或任何其他Context )中使用它,而不必在任何地方定义它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM