2010年7月7日星期三

如何在Toast之上顯示圖像

本練習通過創建一個新的佈局, 把文本及圖像加入, 並使用Toast.setView()把佈局加進Toast中, 從而做到在Toast之上顯示圖像.

在Toast之上顯示圖像

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/buttonshowtoast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Toast"
/>
</LinearLayout>


AndroidImageToast.java
package com.AndroidImageToast;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidImageToast extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonShowToast = (Button)findViewById(R.id.buttonshowtoast);
buttonShowToast.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

Toast myToast = new Toast(AndroidImageToast.this);
LinearLayout toastLayout = new LinearLayout(AndroidImageToast.this);
toastLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView toastImage = new ImageView(AndroidImageToast.this);
TextView toastText = new TextView(AndroidImageToast.this);
toastImage.setImageResource(R.drawable.icon);
toastText.setText("It's a Toast with image and text!");
toastLayout.addView(toastImage);
toastLayout.addView(toastText);
myToast.setView(toastLayout);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.show();


}});

}
}

沒有留言:

發佈留言