今天讲的内容属於简单的元件使用,而我在前面几天已经先有拿来用几次来观察结果,但我一直没有好好提到,今天就来讲讲Toast这个元件,而这个元件也不用在ui画面进行放置的动作。
Toast.makeText(Context context, CharSequence text, int duration).show();
就像是这样,当然我也可以宣告一个String把她显示在toast上。
//在Activity中
String text="Hello";
Toast.makeText(MainActivity.this, text+" Android" , Toast.LENGTH_SHORT).show();
//context也可以只写this,或者用view的话,可以使用view.getContext()
另外要谈到Toast的位置,他的预设位置是在中下的地方,但有方法可以做更改。(setGravity方法)
public void setGravity (int gravity, int xOffset, int yOffset)
String text="Hello";
Toast toast=Toast.makeText(MainActivity.this, text+" Android" , Toast.LENGTH_SHORT);
toast.setGravity(Gravity_CENTER,100,200);
toast.show();
首先先来定义Toast的布局。
toast_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/black">
<ImageView
android:id="@+id/imageView"
android:layout_width="150dp"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_launcher_foreground" />
<TextView
android:id="@+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello Android"
android:textColor="@color/white"/>
</LinearLayout>
大约长这样子:
(因为我最外围布局是使用wrap_content,所以toast出来只会显示有使用到的部分,也就是黑色区块的部分。)
另外activity_main的布局我就加入一颗按钮来监听,按下去则显示Toast。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
而toast的话可以不用写class,可以透过LayoutInflater来操作:
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);//取得布局的layoutinflater
View view = layoutInflater.inflate(R.layout.toast_layout, null);//动态载入toast_layout这个页面生成view
Toast toast = new Toast(MainActivity.this);//新增一个toast(需要一个参数为context)
toast.setDuration(Toast.LENGTH_SHORT);//设定持续时间
toast.setGravity(Gravity.CENTER,0,-200);//设定位置
toast.setView(view);//设定使用toast_layout这个自定义的布局
toast.show();//显示
}
});
}
}
<<: [Android Studio 30天自我挑战] 利用Button切换ImageView的图片
The Chain of Responsibility design pattern avoids ...
原来已经一个月了,想当初充满着犹豫要不要开赛,开赛後又想着会不会断赛,深知真的断赛肯定会後悔,庆幸挺...
JavsScripe是一套非同步的、单执行绪(single-threaded)语言,任务与任务之间必...
今天想偷个懒,先为App加入一点动画, 主要是从欢迎页到登入页的过度动画。 Navigation t...
为了让 Gradle 在运行的时候可以更弹性,Gradle 支援一系列载入建置环境(Build En...