步骤:
设置监听事件步骤
1.事件源,如按键 btn_simple
2.事件 OnClick
3.监听器new OnClickListener
3.绑定事件源与事件 setOnClickListener(new OnClickListener() {}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/btn_simple" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="普通Toast" /> <Button android:id="@+id/btn_toast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="带图片Toast" /> </LinearLayout>
Activity:
public class MainActivity extends Activity { private Button btn_simple; private Button btn_toast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_simple = (Button) findViewById(R.id.btn_simple); btn_toast = (Button) findViewById(R.id.btn_toast); btn_simple.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "简单的文本提示信息", Toast.LENGTH_SHORT).show(); } }); /* * 带图片的Toast */ btn_toast.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //创建Toast Toast toast = new Toast(MainActivity.this); //设置Toast显示位置 toast.setGravity(Gravity.CENTER, 0, 0); //创建一个ImageView ImageView iv = new ImageView(MainActivity.this); iv.setImageResource(R.drawable.tools); //创建容器 LinearLayout ll = new LinearLayout(MainActivity.this); ll.addView(iv); //创建一个文本 TextView tv = new TextView(MainActivity.this); tv.setText("带图片提示信息"); tv.setTextSize(24); tv.setTextColor(Color.MAGENTA); ll.addView(tv); toast.setView(ll); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); } }); } }
时间: 2024-10-12 01:33:56