安卓app_sl3.13xml按钮 onClick属性指定对应的方法与java事件监听器的方法
图像按钮android:onClick="myClick"对应MainActivity.java的myClick方法,点击按钮显示toast提示消息后自动消失
<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:orientation="horizontal" tools:context="com.example.sl3_13.MainActivity" > <Button android:id="@+id/login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登录" /> <ImageButton android:id="@+id/imageButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClick" android:src="@android:drawable/btn_star" /> </LinearLayout>
package com.example.sl3_13; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button login=(Button)findViewById(R.id.login); login.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO 自动生成的方法存根 Toast toast=Toast.makeText(MainActivity.this, "您点击了普通按钮",Toast.LENGTH_SHORT); toast.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void myClick(View view) { Toast toast=Toast.makeText(MainActivity.this, "您点击了图片按钮",Toast.LENGTH_SHORT); toast.show(); } }
欢迎讨论,相互学习。
cdtxw@foxmail.com