gpt4 book ai didi

android - 在任何textview android中将Toast重力设置为左上角

转载 作者:行者123 更新时间:2023-11-29 01:27:17 25 4
gpt4 key购买 nike

我想在我的应用程序的任何 TextView 中将我的 toast 消息设置在顶部|左侧位置,所以我使用了这段代码

public class CustomToast extends Activity {

TextView mTextView1;
TextView mTextView2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_toast);
mTextView1=(TextView)findViewById(R.id.textView);
mTextView2=(TextView)findViewById(R.id.textView2);
mTextView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomAlert( );
}
});
mTextView2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomAlert( );
}
});
}
public void showCustomAlert( )
{

Context context = getApplicationContext();
// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();

// Call toast.xml file for toast layout
View toastRoot = inflater.inflate(R.layout.toast, null);

Toast toast = new Toast(context);

// Set layout to toast
toast.setView(toastRoot);
toast.setGravity(Gravity.TOP|Gravity.LEFT ,0, 0);
toast.setDuration(2000);
toast.show();

}
}

当我运行上面的代码时,toast 每次都显示在屏幕顶部,特别是 TextView ,请参见下图。

最初是两个 TextView 屏幕

enter image description here

当我点击 second textview 时,我得到了这个 toast 位置

enter image description here

知道如何解决这个问题吗?

最佳答案

你需要做的就是根据屏幕上textview的位置来管理Toast的位置。然后你需要每次动态添加 View 的坐标到你的Toast。所以你需要获取 View 的坐标是点击使用:

buttonView.getLocationOnScreen(location);

然后设置Toast的位置:

toast.setGravity(Gravity.TOP|Gravity.LEFT,buttonView.getRight()+5, 
location[1]-10);

以上仅供引用,更清晰的描述思路请见ThisThis .

关于android - 在任何textview android中将Toast重力设置为左上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com