Android——监听事件总结1

Posted Chen_s

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android——监听事件总结1相关的知识,希望对你有一定的参考价值。

各种监听事件

1.按钮 Button
(1)点击监听
btn_1.setOnClickListener(new View.OnClickListener() {

(2)长按监听
btn_1.setOnLongClickListener(new View.OnLongClickListener() {

2.单选框 RadioGroup
radio_gp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

3.复选框 CheckBox(普通内部类)
cb_fuxuan1.setOnCheckedChangeListener(new checkboxcheckedlistener());
cb_fuxuan2.setOnCheckedChangeListener(new checkboxcheckedlistener());

private class checkboxcheckedlistener implements CompoundButton.OnCheckedChangeListener
{

4.上下文菜单 ContextMenu(需要长按才能触发)

changan_menu.setOnCreateContextMenuListener(this);
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//获取值
public boolean onContextItemSelected(MenuItem item) {
item.getItemId()

5.进度条 SeekBar(可拖动)

sbr_td.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

6.开关 开关按钮:ToggleButton 推拉开关 Switch

tb.setOnCheckedChangeListener(new anniucheckedlistener());
private class anniucheckedlistener implements CompoundButton.OnCheckedChangeListener{

 

7.对话框 方法链构造 new AlertDialog.Builder(this)

 

单选对话框
final String[] yanse = {"红","黄","绿","蓝","白"};

 

.setSingleChoiceItems(yanse, 0, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

 

多选对话框
final String[] yanse = {"红","黄","绿","蓝","白"};
final boolean[] bl = {true,true,false,false,false};

 

.setMultiChoiceItems(yanse, bl, new DialogInterface.OnMultiChoiceClickListener() {

public void onClick(DialogInterface dialog, int which, boolean isChecked) {

 

自定义对话框 加载器 getLayoutInflater() setview

 

LayoutInflater layoutInflater = getLayoutInflater();

 

8.进度条 ProgressDialog

 

旋转进度条
final ProgressDialog pd = new ProgressDialog(this);

 

水平进度条
ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

 

9.日期对话框
Calendar cl = Calendar.getInstance();

 

DatePickerDialog datePickerDialog = new DatePickerDialog(this,监听, cl.get(Calendar.YEAR),cl.get(Calendar.MONTH),cl.get(Calendar.DAY_OF_MONTH));

 

datePickerDialog.show();

 


监听 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
}
10.时间对话框

//获取当前日期
//单例模式,设计模式的一种 静态方法
Calendar cl = Calendar.getInstance();

 

TimePickerDialog timePickerDialog = new TimePickerDialog(this,监听,cl.get(Calendar.HOUR),cl.get(Calendar.MINUTE),true);

 

timePickerDialog.show();

 

监听 = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

 


}
}
11.ListView

 

(1)ArrayAdapter

 

//构造适配器
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.listview_layout,list);

 

//设置适配器
listview_1.setAdapter(adapter);

 

//监听事件
listview_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

 

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

 

(2)SimpleAdapter

 

SimpleAdapter simpleAdapter = new SimpleAdapter(this,im,R.layout.simple_layout,str,viewid);

 

simple_1.setAdapter(simpleAdapter);

 

simple_1.setOnItemClickListener();
(3)BaseAdapter

 

12.自动提示文本框
AutoCompleteTextView autv_1 = (AutoCompleteTextView)findViewById(R.id.atv_1);

 

13下拉列表
Spinner sper_1 = (Spinner)findViewById(R.id.sper_1);

 

sper_1.setAdapter(adapter);

 

sper_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

 

14.消息提示
Resources res = Activitywenben.this.getResources();
//1.获取状态栏消息管理器
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//2.构建消息 用Builder构建 方法链调用
Notification nt = new Notification.Builder(this)
//3.交给管理器发出消息
manager.notify(0,nt);

 

 xml

 

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textview1"
            android:text="有链接吗?"
            android:autoLink="all"
            />
        <AutoCompleteTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/autv_1"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="按钮的监听"
            android:id="@+id/btn_1"
            android:background="@drawable/anniu1"
            />
        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/radio_gp">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="是"
                android:id="@+id/rb_shi"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="否"
                android:id="@+id/rb_fou"/>
        </RadioGroup>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="hello world"
            android:id="@+id/et_1"/>

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="复选一"
            android:id="@+id/cb_fuxuan1"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="复选二"
            android:id="@+id/cb_fuxuan2"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="长按触发上下文菜单"
            android:id="@+id/menu_1"/>

        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="100"
            android:id="@+id/sbr_tuodong"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/anniu2"
            android:id="@+id/iv_bian"
            />
        <ToggleButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textOn="开"
            android:textOff="关"
            android:id="@+id/tgb_1"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/swh_1"/>

        <!--对话框-->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发普通对话框"
            android:onClick="putongdhkonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发单选对话框"
            android:onClick="danxuandhkonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发多选对话框"
            android:onClick="duoxuandhkonclick"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发自定义对话框"
            android:onClick="zidingyidhkonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发旋转进度条"
            android:onClick="xuanzhuanjdtonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发水平进度条"
            android:onClick="shuipingjdtonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发日期对话框"
            android:onClick="riqidhkonclick"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="点击触发时间对话框"
            android:onClick="shijiandhkonclick"/>



    </LinearLayout>

</ScrollView>

 

 

 

java

package com.example.chenshuai.test322;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.util.Linkify;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.util.Calendar;

/**
 * Created by chenshuai on 2016/4/1.
 */
public class Jianting extends AppCompatActivity {

    ImageView iv_bian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jiantinglayout);

        //Textview
        TextView textview1 = (TextView)findViewById(R.id.textview1);
        textview1.setAutoLinkMask(Linkify.ALL);

        String linktext = "百度链接 www.baidu.com";
        textview1.setText(linktext);

        //AutoCompleteTextView
        AutoCompleteTextView autv_1 = (AutoCompleteTextView)findViewById(R.id.autv_1);
        String[] str = {"ab","abc","abcd"};

        ArrayAdapter<String> stringArrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,str);

        autv_1.setAdapter(stringArrayAdapter);

        //Button 点击
        Button btn_1 = (Button)findViewById(R.id.btn_1);
        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Jianting.this, "按钮点击监听", Toast.LENGTH_SHORT).show();
            }
        });

        //Button 长按监听
        btn_1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                Toast.makeText(Jianting.this, "按钮长按监听", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        //RadioGroup 的监听
        RadioGroup radio_gp = (RadioGroup)findViewById(R.id.radio_gp);
        radio_gp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                RadioButton rb_shi = (RadioButton) findViewById(R.id.rb_shi);

                RadioButton rb_fou = (RadioButton) findViewById(R.id.rb_fou);

                switch (checkedId) {
                    case R.id.rb_shi:
                        Toast.makeText(Jianting.this, "选中了" + rb_shi.getText(), Toast.LENGTH_SHORT).show();

                    case R.id.rb_fou:
                        Toast.makeText(Jianting.this, "选中了" + rb_fou.getText(), Toast.LENGTH_SHORT).show();

                }

            }
        });

        //显示Edittext的输入内容
        EditText editText = (EditText)findViewById(R.id.et_1);

        String str1 = editText.getText().toString();

        Toast.makeText(Jianting.this, str1, Toast.LENGTH_SHORT).show();


        //checkbox的监听

        CheckBox cb_fuxuan1 = (CheckBox)findViewById(R.id.cb_fuxuan1);
        cb_fuxuan1.setOnCheckedChangeListener(new checkboxcheckedlistener());


        CheckBox cb_fuxuan2 = (CheckBox)findViewById(R.id.cb_fuxuan2);
        cb_fuxuan2.setOnCheckedChangeListener(new checkboxcheckedlistener());

        //menu 菜单 上下文菜单
        Button changan_menu = (Button)findViewById(R.id.menu_1);
        changan_menu.setOnCreateContextMenuListener(this);

        //SeekBar 可拖动进度条
        SeekBar sbr_td = (SeekBar)findViewById(R.id.sbr_tuodong);

        sbr_td.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //开关键控制按钮背景
        iv_bian = (ImageView)findViewById(R.id.iv_bian);

        //开关按钮
        ToggleButton tb = (ToggleButton)findViewById(R.id.tgb_1);

        tb.setOnCheckedChangeListener(new anniucheckedlistener());

        //推拉开关
        Switch swh = (Switch)findViewById(R.id.swh_1);
        swh.setOnCheckedChangeListener(new anniucheckedlistener());
    }

    //普通内部类  checkbox的监听
    private class checkboxcheckedlistener implements CompoundButton.OnCheckedChangeListener
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            CheckBox cb = (CheckBox)buttonView;

            if (isChecked)
            {
                Toast.makeText(Jianting.this, "选中了"+cb.getText(), Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(Jianting.this, "取消选中了"+cb.getText(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    //menu 菜单 上下文菜单
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(1,1,1,"添加");
        menu.add(1,2,2,"删除");
        menu.add(1,3,3,"修改");
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        switch (item.getItemId())
        {
            case 1:
                Toast.makeText(Jianting.this, "触发了添加功能", Toast.LENGTH_SHORT).show();
            case 2:
                Toast.makeText(Jianting.this, "触发了删除功能", Toast.LENGTH_SHORT).show();
            case 3:
                Toast.makeText(Jianting.this, "触发了修改功能", Toast.LENGTH_SHORT).show();
        }
        return super.onContextItemSelected(item);
    }

    private class anniucheckedlistener implements CompoundButton.OnCheckedChangeListener{

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
            {
                iv_bian.setImageResource(R.drawable.anniu1);
            }
            else
            {
                iv_bian.setImageResource(R.drawable.anniu2);
            }
        }
    }
    //普通对话框
    public void putongdhkonclick(View view)
    {
        //普通对话框
        //对话框的构建器
       /* AlertDialog.Builder ab = new AlertDialog.Builder(this);

        ab.setTitle("数据删除");
        ab.setMessage("确定删除吗?");
        ab.setPositiveButton("确定",null);
        ab.setNegativeButton("取消",null);
        ab.setCancelable(false);
        ab.show();*/

        //方法链的方法
       new AlertDialog.Builder(this)
               .setTitle("数据删除")
               .setMessage("确定删除吗?")
               .setPositiveButton("确定",null)
               .setNegativeButton("取消",null)
               .setCancelable(false)
               .show();
    }

    public void danxuandhkonclick(View view)
    {
        final String[] yanse = {"红","黄","绿","蓝","白"};
        //方法链
        new AlertDialog.Builder(this)

                .setTitle("单选对话框")
                .setSingleChoiceItems(yanse, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Toast.makeText(Jianting.this, "选中了" + yanse[which], Toast.LENGTH_SHORT).show();

                        //移除属性 dialog.dismiss(); 选中一个就会关闭
                    }
                })
                .setNeutralButton("确定", null)//普通按钮
                .setCancelable(false)
                .show();
    }

    public void duoxuandhkonclick(View view)
    {
        final String[] yanse = {"红","黄","绿","蓝","白"};
        final boolean[] bl = {true,true,false,false,false};
        //方法链

        new AlertDialog.Builder(this)
                .setTitle("多选对话框")
                .setMultiChoiceItems(yanse, bl, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                        if (isChecked) {
                            Toast.makeText(Jianting.this, "选中了" + yanse[which], Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(Jianting.this, "取消选中了" + yanse[which], Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //遍历数组 foreach循环
                        for (boolean b : bl) {
                            try {
                                Thread.sleep(100);
                            } catch (Exception ex) {


                            }Toast.makeText(Jianting.this, "取值"+b, Toast.LENGTH_SHORT).show();

                        }
                    }
                })
                .setCancelable(false)
                .show();
    }

    //自定义对话框
    public void zidingyidhkonclick(View view)
    {
        //1.获取加载器
        LayoutInflater layoutInflater = getLayoutInflater();
        //2.用加载器加载文件
        final View view2 = layoutInflater.inflate(R.layout.loginlayout, null);

        //方法链构造页面加两个按钮
        new AlertDialog.Builder(this)
                .setView(view2)//兼容性好,比较适用
                //.setView(R.layout.loginlayout)
                .setNegativeButton("取消", null)
                .setPositiveButton("登陆", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        EditText user = (EditText) view2.findViewById(R.id.et_username);

                        EditText pas = (EditText) view2.findViewById(R.id.et_password);
                    }
                })

                .show();
    }
    //旋转进度条
    public void xuanzhuanjdtonclick(View view)
    {
        final ProgressDialog pd = new ProgressDialog(this);

        pd.setMessage("正在加载");
        pd.show();

        //创建thread实例  =【重写run方法  启动多线程
        new Thread()
        {
            @Override
            public void run() {
                super.run();

                try{

                    Thread.sleep(3000);
                }
                catch (Exception ex){}

                pd.dismiss();//关闭
            }
        }.start();
    }

    //水平进度条
    public void shuipingjdtonclick(View view)
    {
        ProgressDialog pd = new ProgressDialog(this);

        pd.setMessage("正在加载");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.show();
    }

    //日期对话框
    public void riqidhkonclick(View view)
    {
        //获取当前日期
        //单例模式,设计模式的一种  静态方法
        Calendar cl = Calendar.getInstance();

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                Toast.makeText(Jianting.this, year+"-"+ (monthOfYear+1) + "-" + dayOfMonth, Toast.LENGTH_SHORT).show();
            }
        },cl.get(Calendar.YEAR),cl.get(Calendar.MONTH),cl.get(Calendar.DAY_OF_MONTH));

        datePickerDialog.setCancelable(false);
        datePickerDialog.show();

    }

    //时间对话框
    public void shijiandhkonclick(View view)
    {
        //获取当前日期
        //单例模式,设计模式的一种  静态方法
        Calendar cl = Calendar.getInstance();

        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                Toast.makeText(Jianting.this, hourOfDay+":"+minute , Toast.LENGTH_SHORT).show();
            }
        },cl.get(Calendar.HOUR),cl.get(Calendar.MINUTE),true);

        timePickerDialog.setCancelable(false);
        timePickerDialog.show();

    }

}

 

以上是关于Android——监听事件总结1的主要内容,如果未能解决你的问题,请参考以下文章

多种监听事件处理方法

Android_基于监听的事件处理机制

是否可以监听物理 Android 后退按钮的触摸?

Android 事件分发事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup )(代码片段

归纳总结Android的点击事件

Android 键盘事件触发以及监听