Android技术学习,更多知识请访问
本文通过罗老师的视频总结得来的
1,一个xml文件
<LinearLayout xmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><Button android:id="@+id/commonButton" android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/myButton1"/><Button android:id="@+id/imageButton" android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_gravity="center"android:background="@drawable/av" android:text="@string/button2"/></LinearLayout>
2通常用的是实现OnClickListener,OnTouchListener,OnFocusChangeListener,OnKeyListener
//实现几个常用的点击事件public class MainActivity extends Activity implements OnClickListener,OnTouchListener,OnFocusChangeListener,OnKeyListener{private int value = 1;//改变按钮的大小private Button commonButton;private Button imageButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);commonButton = (Button)this.findViewById(monButton);imageButton = (Button)this.findViewById(R.id.imageButton);//注册事件commonButton.setOnClickListener(this);imageButton.setOnClickListener(this);imageButton.setOnTouchListener(this);imageButton.setOnFocusChangeListener(this);imageButton.setOnKeyListener(this);}@Overridepublic 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;}//@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {// TODO Auto-generated method stubif(KeyEvent.ACTION_DOWN == event.getAction()){//按下事件v.setBackgroundResource(R.drawable.a2);}else if(KeyEvent.ACTION_UP == event.getAction()){v.setBackgroundResource(R.drawable.a3);}return false;}//焦点发生变化触发@Overridepublic void onFocusChange(View v, boolean hasFocus) {// TODO Auto-generated method stubif(hasFocus){imageButton.setBackgroundResource(R.drawable.a2);}else{imageButton.setBackgroundResource(R.drawable.a3);}}//触摸时候触发@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubif(event.getAction() == MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.a2);}else if(event.getAction() == MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.a3);}return false;}//点击时候触发@SuppressWarnings("deprecation")@Overridepublic void onClick(View v) {// TODO Auto-generated method stubButton button = (Button)v;if(value == 1 && button.getWidth() == getWindowManager().getDefaultDisplay().getWidth()){value = -1;}else if(value == -1 && button.getWidth() < 10){value = 1;}button.setWidth(button.getWidth()+(int)(button.getWidth()*0.1)*value);button.setHeight(button.getHeight()+(int)(button.getHeight()*0.1)*value);}
3.实现的效果
Android技术学习,更多知识请访问
如果觉得《Android 中屏幕点击事件的实现2》对你有帮助,请点赞、收藏,并留下你的观点哦!