android 中的事件处理

xiaoxiao2021-02-28  15

(1)点击事件

private void initView() { mbtnst= (Button) findViewById(R.id.btndialog); mbtnst.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.btndialog: //创建对话框的builder对象 AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle("我是标题!"); builder.setMessage("我是消息messa!"); builder.setIcon(R.drawable.cat); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "点击了确定", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("否定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "点击了否定", Toast.LENGTH_SHORT).show(); } }); builder.show(); break; } }

(2)长按事件

public class MainActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener{ private void initView() { mbtnmy= (Button) findViewById(R.id.mydialog); mbtnmy.setOnLongClickListener(this); } @Override public boolean onLongClick(View v) { Toast.makeText(MainActivity.this,"长按事件",Toast.LENGTH_LONG).show(); return true; } (3)按键事件

private void initView() { metin= (EditText) findViewById(R.id.etin); metin.setOnKeyListener(this); } public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener,View.OnKeyListener{ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (event.getAction()){ case KeyEvent.ACTION_DOWN: Toast.makeText(MainActivity.this,"按键落下",Toast.LENGTH_LONG).show(); break; case KeyEvent.ACTION_UP: EditText et= (EditText) v; Toast.makeText(MainActivity.this,"按键弹起,键入的是:"+et.getText().toString(), Toast.LENGTH_LONG).show(); break; default: break; } return false; }

转载请注明原文地址: https://www.6miu.com/read-1450001.html

最新回复(0)