android – 尝试以编程方式在显示列表视图后设置LISTVIEW内的SWITCH状态

android – 尝试以编程方式在显示列表视图后设置LISTVIEW内的SWITCH状态,第1张

概述所以我有一个警报列表,我将它绑定到listview,lstAlarms.在我的自定义ListView布局中,我还有一个开关,我想根据警报的状态以编程方式设置.我想在刚刚显示ListView后立即执行此 *** 作. 请参阅下面的代码. 显示ListView的方法是DisplayAlarmList(). 我试图用来设置开关状态的方法是InitSwitches(),它在DisplayAlarmList()内部 所以我有一个警报列表,我将它绑定到ListvIEw,lstAlarms.在我的自定义ListVIEw布局中,我还有一个开关,我想根据警报的状态以编程方式设置.我想在刚刚显示ListVIEw后立即执行此 *** 作.

请参阅下面的代码.
显示ListVIEw的方法是displayAlarmList().
我试图用来设置开关状态的方法是InitSwitches(),它在displayAlarmList()内部被调用.
在onCreate()方法中调用displayAlarmList().

public voID displayAlarmList(){    final String[] columns = {Database.getAlarmID(),Database.getAlarmTime(),Database.getAlarmname(),Database.getAlarmStatus(),Database.getAlarmRepeats()};    Cursor c = Database.selectAlarm(db,Database.gettablename(),columns,null,null);    int[] to = new int[]{            R.ID.alarmID,R.ID.alarmTime,R.ID.alarmname,R.ID.alarmStatus,R.ID.alarmRepeats,};    SimpleCursorAdapter ca = new SimpleCursorAdapter(this,R.layout.alarm_info,c,to,0);    lstAlarm.setAdapter(ca);    InitSwitches();    lstAlarm.setonItemClickListener(new OnItemClickListener()    {        @OverrIDe        public voID onItemClick(AdapterVIEw<?> ListVIEw,VIEw vIEw,int position,long ID)        {            Alarm alarm = new Alarm();            Cursor selectedCursor = (Cursor) ListVIEw.getItemAtposition(position);            Switch s = (Switch) vIEw.findVIEwByID(R.ID.alarmSwitch);            String whereArgs = Integer.toString(selectedCursor.getInt(selectedCursor.getColumnIndexOrThrow(Database.getAlarmID())));            Cursor data = Database.Rawquery(db,"SELECT * FROM " + Database.gettablename() + " WHERE " + Database.getAlarmID() + " = " + whereArgs);            if (data.movetoFirst())            {                alarm.setAlarmID(data.getString(data.getColumnIndexOrThrow(Database.getAlarmID())));                alarm.setAlarmname(data.getString(data.getColumnIndexOrThrow(Database.getAlarmname())));                alarm.setAlarmTime(data.getString(data.getColumnIndexOrThrow(Database.getAlarmTime())));                alarm.setAlarmSound(data.getString(data.getColumnIndexOrThrow(Database.getAlarmSound())));                alarm.setAlarmRepeats(data.getString(data.getColumnIndexOrThrow(Database.getAlarmRepeats())));                alarm.setAlarmStatus(data.getString(data.getColumnIndexOrThrow(Database.getAlarmStatus())));            }            Intent i = new Intent(vIEw.getContext(),ScreenEdit.class);            i.putExtra("editAlarm",new Gson().toJson(alarm));            startActivityForResult(i,EDIT_ALARM);        }    });}public voID InitSwitches(){    VIEw v;    Switch s;    int index = 0;    String query = "Select " + Database.getAlarmID() + "," + Database.getAlarmStatus() + " FROM " + Database.gettablename();    Cursor statuses = Database.Rawquery(db,query);    while (statuses.movetoNext())    {        v = lstAlarm.getAdapter().getVIEw(index++,null);        s = (Switch) v.findVIEwByID(R.ID.alarmSwitch);        if (statuses.getString(statuses.getColumnIndexOrThrow(Database.getAlarmStatus())).equals("ON")){            s.toggle();        }        else{                        }    }}

ScreenShot of app

从屏幕截图中可以看出,第二行中的开关应该是ON,但事实并非如此.我也尝试了InvilIDateVIEw(),但没有工作.请帮忙.

解决方法 问题是ListVIEw是不断重绘的那些视图之一,这意味着这很糟糕,因为它会在重绘时失去状态

if (statuses.getString(statuses.getColumnIndexOrThrow(Database.getAlarmStatus())).equals("ON")){    s.toggle();}

首先创建AlarmItem ……你应该根据自己的需要制作它.这是我的

public class AlarmItem {    private String alarmname;    private String alarmDescption;    private boolean state;    private long ID;    public AlarmItem(String alarmname,String alarmDescption,long ID,boolean state) {        this.alarmname = alarmname;        this.alarmDescption = alarmDescption;        this.ID = ID;        this.state = state;    }    public long getID() {        return ID;    }    public voID setID(long ID) {        this.ID = ID;    }    public String getAlarmname() {        return alarmname;    }    public voID setAlarmname(String alarmname) {        this.alarmname = alarmname;    }    public String getAlarmDescption() {        return alarmDescption;    }    public voID setAlarmDescption(String alarmDescption) {        this.alarmDescption = alarmDescption;    }    public boolean getState() {        return state;    }    public voID setState(boolean state) {        this.state = state;    }}

现在我们需要一个CustomSwitch类,因为:LINK

import androID.content.Context;import androID.util.AttributeSet;import androID.Widget.Switch;public class CustomSwitch extends Switch {    private OnCheckedchangelistener mListener;    public CustomSwitch(Context context) {        super(context);    }    public CustomSwitch(Context context,AttributeSet attrs) {        super(context,attrs);    }    public CustomSwitch(Context context,AttributeSet attrs,int defStyleAttr) {        super(context,attrs,defStyleAttr);    }    public CustomSwitch(Context context,int defStyleAttr,int defStyleRes) {        super(context,defStyleAttr,defStyleRes);    }    @OverrIDe    public voID setonCheckedchangelistener(OnCheckedchangelistener Listener) {        // Do not call supper method        mListener = Listener;    }    @OverrIDe    public voID setChecked(boolean checked) {        super.setChecked(checked);        if (mListener != null) {            mListener.onCheckedChanged(this,checked);        }    }    public voID setCheckedProgrammatically(boolean checked) {        // You can call super method,it doesn't have a Listener... he he :)        super.setChecked(checked);    }}

创建一个布局文件并将其命名为alarm_List_item.xml

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"                androID:layout_wIDth="match_parent"                androID:layout_height="50dp"                androID:orIEntation="vertical">    <com.example.alarm.List.CustomSwitch        androID:ID="@+ID/alarmSwitch"        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_alignParentRight="true"        androID:layout_centerVertical="true"        androID:layout_marginRight="10dp"/>    <linearLayout        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:layout_marginleft="5dp"        androID:layout_toleftOf="@ID/alarmSwitch"        androID:orIEntation="vertical">        <TextVIEw            androID:ID="@+ID/tvAlarmname"            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:layout_margintop="5dp"            androID:text="Alarm name"            androID:textSize="18sp"/>        <TextVIEw            androID:ID="@+ID/tvAlarmDesc"            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:layout_margintop="5dp"            androID:text="Alarm description"            androID:textSize="15sp"/>    </linearLayout></relativeLayout>

现在主要布局 – > activity_main.xml中

<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"              androID:layout_wIDth="match_parent"              androID:layout_height="match_parent"              androID:orIEntation="vertical">    <ListVIEw        androID:ID="@+ID/lvAlarms"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"/></linearLayout>

现在我们需要一个负责绘制项目及其处理的适配器.将类命名为AlarmAdapter

import androID.content.Context;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.Widget.BaseAdapter;import androID.Widget.Compoundbutton;import androID.Widget.TextVIEw;import java.util.List;public class AlarmAdapter extends BaseAdapter {    private List<AlarmItem> listofAlarms;    private Context context;    private OnAlarmCheckedchangelistener mCallback;    // avoID constant allocation    private VIEw tmpVIEw;    private AlarmItemVIEwHolder mHolder;    private AlarmItem tmpItem;    public AlarmAdapter(List<AlarmItem> listofAlarms,Context context,OnAlarmCheckedchangelistener callBack) {        this.listofAlarms = listofAlarms;        this.context = context;        mCallback = callBack;    }    @OverrIDe    public int getCount() {        return listofAlarms == null ? 0 : listofAlarms.size();    }    @OverrIDe    public AlarmItem getItem(int i) {        return listofAlarms == null ? null : listofAlarms.get(i);    }    @OverrIDe    public long getItemID(int i) {        return 0;    }    @OverrIDe    public VIEw getVIEw(final int i,VIEwGroup vIEwGroup) {        tmpItem = listofAlarms.get(i);        if (vIEw == null) {            LayoutInflater inflater = LayoutInflater.from(context);            tmpVIEw = inflater.inflate(R.layout.alarm_List_item,false);            mHolder = new AlarmItemVIEwHolder(tmpVIEw);            tmpVIEw.setTag(mHolder);        }        else {            tmpVIEw = vIEw;            mHolder = (AlarmItemVIEwHolder) vIEw.getTag();        }        mHolder.getAlarmnameTextVIEw().setText(tmpItem.getAlarmname());        mHolder.getAlarmDescriptionTextVIEw().setText(tmpItem.getAlarmDescption());        mHolder.getSwitch().setCheckedProgrammatically(tmpItem.getState());        mHolder.getSwitch().setonCheckedchangelistener(new Compoundbutton.OnCheckedchangelistener() {            @OverrIDe            public voID onCheckedChanged(Compoundbutton compoundbutton,boolean b) {                listofAlarms.get(i).setState(b);                mCallback.onAlarmStateChanged(listofAlarms.get(i),i);            }        });        return tmpVIEw;    }    public voID clear() {        listofAlarms.clear();        notifyDataSetChanged();    }    public voID refill(List<AlarmItem> listofAlarms) {        this.listofAlarms = listofAlarms;        notifyDataSetChanged();    }    public voID toggleAllSwitches() {        for (AlarmItem item : listofAlarms) {            item.setState(!item.getState());        }        notifyDataSetChanged();    }    public interface OnAlarmCheckedchangelistener {        public voID onAlarmStateChanged(AlarmItem item,int postionInList);    }    private class AlarmItemVIEwHolder {        VIEw base;        CustomSwitch mSwitch;        TextVIEw mAlarmname;        TextVIEw mAlarmDescription;        public AlarmItemVIEwHolder(VIEw base) {            this.base = base;        }        public CustomSwitch getSwitch() {            if (mSwitch == null) {                mSwitch = (CustomSwitch) base.findVIEwByID(R.ID.alarmSwitch);            }            return mSwitch;        }        public TextVIEw getAlarmnameTextVIEw() {            if (mAlarmname == null) {                mAlarmname = (TextVIEw) base.findVIEwByID(R.ID.tvAlarmname);            }            return mAlarmname;        }        public TextVIEw getAlarmDescriptionTextVIEw() {            if (mAlarmDescription == null) {                mAlarmDescription = (TextVIEw) base.findVIEwByID(R.ID.tvAlarmDesc);            }            return mAlarmDescription;        }    }}

现在终于进入了MainActivity

import androID.app.Actionbar;import androID.os.Bundle;import androID.os.Handler;import androID.os.Looper;import androID.support.v7.app.ActionBaractivity;import androID.vIEw.VIEw;import androID.Widget.AdapterVIEw;import androID.Widget.ListVIEw;import androID.Widget.Toast;import java.util.ArrayList;import java.util.List;public class MainActivity extends ActionBaractivity implements AdapterVIEw.OnItemClickListener,AlarmAdapter.OnAlarmCheckedchangelistener {    private ListVIEw ListVIEw;    private AlarmAdapter adapter;    private Toast toast;    private Handler handler;    private Runnable handlerRunnable;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        // Make a nice actionbar Title        Actionbar ab = getActionbar();        if (ab != null) {            ab.setTitle("Alarm List");        }        ListVIEw = (ListVIEw) findVIEwByID(R.ID.lvAlarms);        // Simulating alarms from database. You need to convert your items to these        List<AlarmItem> alarmsFromDb = new ArrayList<>();        alarmsFromDb.add(new AlarmItem("Alarm 1","Lalalala",1,true));        alarmsFromDb.add(new AlarmItem("Alarm 2","something",2,false));        alarmsFromDb.add(new AlarmItem("Alarm 3","gfdgdf",3,true));        alarmsFromDb.add(new AlarmItem("Alarm 4","sda",4,true));        alarmsFromDb.add(new AlarmItem("Alarm 5","yxcxyc",5,false));        alarmsFromDb.add(new AlarmItem("Alarm 6","dsfsd",6,false));        adapter = new AlarmAdapter(alarmsFromDb,this,this);        ListVIEw.setAdapter(adapter);        ListVIEw.setonItemClickListener(this);        // Toggle all switches after 5s... this is what you need,right?        handlerRunnable = new Runnable() {            @OverrIDe            public voID run() {                adapter.toggleAllSwitches();                showToast("All switches toggeled :)");            }        };        handler = new Handler(Looper.getMainLooper());        handler.postDelayed(handlerRunnable,5 * 1000);    }    @OverrIDe    protected voID onDestroy() {        super.onDestroy();        if (handler != null) {            handler.removeCallbacks(handlerRunnable);            handler = null;            handlerRunnable = null;        }    }    private voID showToast(String str) {        if (toast != null) {            toast.cancel();        }        toast = Toast.makeText(this,str,Toast.LENGTH_SHORT);        toast.show();    }    @OverrIDe    public voID onAlarmStateChanged(AlarmItem item,int postionInList) {        String onOff = item.getState() ? "ON" : "OFF";        showToast("Alarm " + item.getAlarmname() + " is: " + onOff);    }    @OverrIDe    public voID onItemClick(AdapterVIEw<?> parent,long ID) {        AlarmItem item = adapter.getItem(position);        showToast("Alarm " + item.getAlarmname() + " clicked");    }}

如果您有任何问题,这是完整的androID工作室项目:LINK

现在,您只需将数据库中的结果转换为此列表或修改AlarmItem和UI.此解决方案将起作用,您已在适配器中使用了一些有用的方法.

快乐的编码!

总结

以上是内存溢出为你收集整理的android – 尝试以编程方式在显示列表视图后设置LISTVIEW内的SWITCH状态全部内容,希望文章能够帮你解决android – 尝试以编程方式在显示列表视图后设置LISTVIEW内的SWITCH状态所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1127806.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存