在Android中,我想在屏幕底部显示一条祝酒消息,我尝试了以下操作:
Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG).show();
它不起作用,如何正确执行?
在Android中,我想在屏幕底部显示一条祝酒消息,我尝试了以下操作:
Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG).show();
它不起作用,如何正确执行?
Answers:
自定义吐司的布局文件
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="5dp" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />
.java文件,用于按钮单击事件上的自定义吐司
public class MainActivity extends Activity {
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonToast);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));
// set a dummy image
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Button is clicked!");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}
}
在koltin中显示/设置文本重力在中心(水平)
fun Context.longToast(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG)
.apply {
view.findViewById<TextView>(android.R.id.message)?.gravity = Gravity.CENTER
}
.show()
}
以下代码可用于显示Toast消息
Toast tt = Toast.makeText(MainActivity.this,"Your text displayed here", Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();