Android 更改 Toast 的預設位置,androidtoast

來源:互聯網
上載者:User

Android 更改 Toast 的預設位置,androidtoast

Android中Toast的預設位置在螢幕靠近底部的位置,這個預設位置有時候並不合適。比如頁面上內容較少時,內容一般集中在螢幕上半部分,使用者的注意力也集中在螢幕上半部分,預設位置的Toast使用者可能沒有注意到。還有可能是預設位置的Toast被使用者的手擋住了。實踐中感覺將Toast顯示在螢幕的中部或中上部會比較好。如何修改Toast的預設位置呢?下面做一個簡單的例子來示範一下。

先上:

布局檔案activity_toast.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClickDefaultToast"        android:text="點擊顯示預設位置的Toast" />    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClickCenterToast"        android:text="點擊顯示置中位置的Toast" />    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClickTopToast"        android:text="點擊顯示置中上部位置的Toast" /></LinearLayout>

後台ToastActivity.java代碼如下:

package chengyujia.demo.aty;import android.os.Bundle;import android.view.Display;import android.view.Gravity;import android.view.View;import android.widget.Toast;import chengyujia.demo.R;public class ToastActivity extends BaseActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_toast);    }    public void onClickDefaultToast(View v) {        Toast.makeText(this, "預設位置的Toast", Toast.LENGTH_LONG).show();    }    public void onClickCenterToast(View v) {        Toast toast = Toast.makeText(this, "置中位置的Toast", Toast.LENGTH_LONG);        toast.setGravity(Gravity.CENTER, 0, 0);        toast.show();    }    public void onClickTopToast(View v) {        Display display = getWindowManager().getDefaultDisplay();        // 擷取螢幕高度        int height = display.getHeight();        Toast toast = Toast.makeText(this, "置中上部位置的Toast", Toast.LENGTH_LONG);        // 這裡給了一個1/4螢幕高度的y軸位移量        toast.setGravity(Gravity.TOP, 0, height / 4);        toast.show();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.