【问题标题】:Android get toast positionAndroid获得吐司位置
【发布时间】:2015-09-15 10:07:26
【问题描述】:

我能够获取每条(默认)toast 消息,但我想向其中添加应用程序图标。如何从 toast 视图/小部件中获取位置?

我的 toast catcher 是 AccessibilityService,我希望 AccessibilityEvent 有一些有用的东西,但我没有找到包含所需数据的属性。

编辑:CyanogenMod 添加了它,我想用我的应用程序将它实现到股票 android 中。

【问题讨论】:

  • 您需要 toast 位置还是要为其添加图标?
  • 因为 toast 来自不同的应用程序,我不允许编辑 toast。我的想法是覆盖应用程序图标,因此我需要这个位置。还有其他方法吗?
  • 抱歉,我不确定我明白了,所以你想通过用另一个视图覆盖 toast 来隐藏它,对吧?
  • 我添加了一个示例图像,我想要它;)
  • ooook 知道了,我有一个想法,但我不确定它是否可行,让我发布它:)

标签: android android-toast


【解决方案1】:

你可以改变Toast Message的位置

setGravity(int gravity, int xOffset, int yOffset)

你知道你的 Toast 消息位置,你可以简单地设置你的图标位置 doc

【讨论】:

  • toast 不在他的应用程序中,因此他无法使用 setGravity 访问它:S
【解决方案2】:

你能试试自定义吐司吗?

附上相同的屏幕截图。

custom_toast_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toastParent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#F08080"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginRight="10dp"
        android:contentDescription="@string/app_name" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF" />

</LinearLayout>

Java类中:

private void displayToast(){
   LayoutInflater inflater = getLayoutInflater();
   View layout = inflater.inflate(R.layout.custom_toast_view, (ViewGroup) findViewById(R.id.toastParent));
   ImageView image = (ImageView) layout.findViewById(R.id.image);
   image.setImageResource(R.drawable.ic_launcher);
   TextView text = (TextView) layout.findViewById(R.id.text);
   text.setText("Hello! This is a custom toast!");
   Toast toast = new Toast(getApplicationContext());
   toast.setDuration(Toast.LENGTH_LONG);
   toast.setView(layout);
   toast.show();
}

希望这会对你有所帮助。

【讨论】:

  • 我的应用程序 (play.google.com/store/apps/…) 会抓住每一个祝酒词。所以,我不能使用自定义布局。我不想禁用原始吐司并显示自定义吐司
【解决方案3】:

使用以下代码,您可以获得从屏幕底部默认的 Toast Y 偏移量:

int i = Resources.getSystem().getIdentifier("toast_y_offset", "dimen", "android");
int bottomOffset = getResources().getDimensionPixelSize(i);

然后只需将您的图像放在屏幕底部,底部填充 == bottomOffset

回答“我从哪里得到左边的位置?”:

Toast 使用 android:layout_gravity="center_horizo​​ntal" 来对齐文本和默认文本大小。因此,您可以计算该文本将占用多少空间(如果您知道确切的文本是什么):Calculating width of a string on Android。那么left offset可以计算为(screenWidth - textWidth) / 2

【讨论】:

  • 我在哪里得到左边的位置?
  • 如果我无法从其他地方读取数据,这可能是唯一可能的方法(手动计算)。
猜你喜欢
  • 2020-04-25
  • 2019-03-31
  • 2013-10-21
  • 2015-04-23
  • 2023-02-15
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多