如何在开关onclicklistener android

时间:2015-07-02 08:23:26

标签: android android-listview onclicklistener onitemclicklistener uiswitch

我正在创建一个Android应用程序。我想要的是,当用户单击一行中的开关时,它会调用listview的onitemclicklistener。之前,我试图在我的customAdapter中的switch的onclicklistener上调用listview的itemclicklistener,但是它会抛出一个错误。如果我没办法达到我想要的结果,请告诉我另一种方法。如果你想知道为什么我需要listview的itemclick在switch的onclick中被调用是因为itemclick是我可以获得行ID的唯一方法,我将用它来更新行。

提前谢谢你。 :)

这是listview的活动代码:

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewForm extends Activity {
    private CustomCursorAdapter customAdapter;
    private TodoItemDatabase td;
    private ListView lv;
    private Switch swi;
    int devId, devPos;
    long devId2;
    String devName;
    int devWatt, devStat;
    //for timer
    Timer timer;
    TimerTask timerTask;
    Handler handler, adapter;
    //for bill compute
    int totalWatt;
    int totalHour = 1;
    double wattHourPerDay, kiloWattPerDay, kiloWattPerMonth, billPerMonth; 
    int timerFirstRun;
    double costPerMonth = 8.5568 ;
    //int delay = 3600000;
    int delay = 50000;
    TextView lblBillVal;
    //double costPerMonth = .10 ;
    OnItemClickListener itemClick;

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

        lv = (ListView)findViewById(R.id.list_data);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        lblBillVal = (TextView)findViewById(R.id.lblBillValue);
        lblBillVal.setText("");

        swi = (Switch)findViewById(R.id.switch1);
        //itemClick

        itemClick = new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
                // TODO Auto-generated method stub
                Log.d("batelec", "id: "+id+" pos: "+pos);
                TodoItemDatabase td = new TodoItemDatabase(getBaseContext());
                int x = Integer.valueOf(String.valueOf(id));
                Cursor cur = td.getOneRow(x);
                if(cur != null){
                    if(cur.moveToFirst()){
                        Log.d("batelec", "inside onitemclick, cur count: "+cur.getCount());
                        devStat = cur.getInt(cur.getColumnIndex(cur.getColumnName(3)));
                        Log.d("batelec", "1st devStat: "+devStat);
                        if(devStat == 0){
                            devStat = 1;
                        }
                        else{
                            devStat = 0;
                        }

                        devId = cur.getInt(cur.getColumnIndex(cur.getColumnName(0)));
                        devName = cur.getString(cur.getColumnIndex(cur.getColumnName(1)));
                        devWatt = cur.getInt(cur.getColumnIndex(cur.getColumnName(2)));
                        //devStat
                        Log.d("batelec", "2nd devStat: "+devStat);
                        td.updateStat(new TodoItem(devId, devName, devWatt, devStat));

                        CustomCursorAdapter cr = new CustomCursorAdapter(ListViewForm.this, td.getAllData());
                        cr.notifyDataSetChanged();
                        lv.setAdapter(cr);
                    }

                }
            }

        };
        lv.setOnItemClickListener(itemClick);
        //itemLongClick
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id){
                Log.d("batelec", "longclick");

                return onLongListItemClick(v, pos, id);
            }
        });

        td = new TodoItemDatabase(this);
        new Handler().post(new Runnable(){
            @Override
            public void run(){
                customAdapter = new CustomCursorAdapter(ListViewForm.this, td.getAllData());
                lv.setAdapter(customAdapter);
            }
        });

        //useHandler();
    }
    //itemLongClick
    protected boolean onLongListItemClick(View v, final int pos, long id) {
        Log.d("batelec", "onLongListItemClick id= " + id + " position= " + pos);

        devId2 = id;
        devPos = pos;
        final Dialog dialog = new Dialog(ListViewForm.this);
        dialog.setContentView(R.layout.dialog_form_design);
        dialog.setTitle("Option");
        Button btnEdit = (Button)dialog.findViewById(R.id.dialogBtnEdit);
        Button btnDelete = (Button)dialog.findViewById(R.id.dialogBtnDelete);

        btnEdit.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                TodoItemDatabase td = new TodoItemDatabase(ListViewForm.this);
                Cursor cur = td.getAllData();

                if(cur!=null){
                    if(cur.moveToFirst()){
                        cur.moveToPosition(pos);
                        devId = cur.getInt(cur.getColumnIndex("_id"));
                        devName = cur.getString(cur.getColumnIndex("deviceName"));
                        devWatt = cur.getInt(cur.getColumnIndex("deviceWattage"));
                        devStat = cur.getInt(cur.getColumnIndex("deviceStatus"));
                        Log.d("batelec", "devID: "+devId+" devName: "+devName+" devWatt: "+devWatt+" devStat: "+devStat);
                    }
                }
                Intent i = new Intent(getBaseContext(),AddDeviceForm.class);
                Bundle b = new Bundle();
                Log.d("batelec", "sent id: "+devId);
                b.putInt("xtraDevId", devId);
                b.putString("xtraDevName", devName);
                b.putInt("xtraWatt", devWatt);
                b.putInt("xtraStat", devStat);
                Log.d("batelec", "sent devStat: "+devStat);
                i.putExtras(b);
                startActivity(i);
                finish();
            }
        });

        btnDelete = (Button)dialog.findViewById(R.id.dialogBtnDelete);
        btnDelete.setOnClickListener(new OnClickListener(){
            public void onClick(View v){

                TodoItemDatabase td = new TodoItemDatabase(ListViewForm.this);
                Cursor cur = td.getAllData();

                if(cur!=null){
                    if(cur.moveToFirst()){
                        cur.moveToPosition(pos);
                        devId = cur.getInt(cur.getColumnIndex("_id"));
                        devName = cur.getString(cur.getColumnIndex("deviceName"));
                        devWatt = cur.getInt(cur.getColumnIndex("deviceWattage"));
                        devStat = cur.getInt(cur.getColumnIndex("deviceStatus"));
                        devPos = pos;
                        Log.d("batelec", "devID: "+devId+" devName: "+devName+" devWatt: "+devWatt+" devStat: "+devStat+" devPos: "+devPos);
                    }
                }
                Bundle b = new Bundle();
                b.putInt("xtraId", devId);
                b.putInt("xtraPos", devPos);
                DialogFragment deleteDiag = new DeleteDialog();
                deleteDiag.setArguments(b);
                deleteDiag.show(getFragmentManager(), "deleteDevice");
            }
        });

        dialog.show();
        Log.d("batelec", "showing dialog");
        return true;
    }

    public void useHandler(){
        handler = new Handler();
        handler.postDelayed(runnable, delay);
    }
    public void stopRunnable(View v){
        handler.removeCallbacks(runnable);
    }

    private Runnable runnable = new Runnable(){
        @Override
        public void run(){
            TodoItemDatabase td = new TodoItemDatabase(getBaseContext());
            Cursor cur = td.getActiveDevice();

            if(timerFirstRun == 0){
                timerFirstRun++;
                Log.d("batelec", "timer = 0");
            }
            else{
                try{
                    if(cur != null){
                        Toast.makeText(getBaseContext(), "1 hour elapsed", Toast.LENGTH_LONG).show();

                        /*cur.moveToFirst();
                        for(int x = 1; x <= cur.getCount(); x++){
                            int id = cur.getInt(cur.getColumnIndex("_id"));
                            String name = cur.getString(cur.getColumnIndex("deviceName"));
                            int watt = cur.getInt(cur.getColumnIndex("deviceWattage"));
                            int stat = cur.getInt(cur.getColumnIndex("deviceStatus"));
                            Log.d("batelec", "id: " + id + " name: " + name + " watt: " + watt + " status: " + stat);
                            totalWatt = totalWatt + watt;
                            cur.moveToNext();
                        }*/
                        totalWatt = 125;
                        Log.d("batelec", "total hour: "+totalHour);
                        wattHourPerDay = totalWatt * totalHour;//all active device wattage * hours it is active

                        Log.d("batelec", "wattPerHour: "+wattHourPerDay+" (totalWatt * totalHour)");
                        kiloWattPerDay = wattHourPerDay / 1000;//all device watts divided by 1000 watts = 1 kW

                        Log.d("batelec", "kilowatt per day: "+kiloWattPerDay+" (wattPerHour / 1000)");
                        kiloWattPerMonth = (wattHourPerDay * 30) / 1000;//watts per month

                        Log.d("batelec", "kiloWatt per month: "+kiloWattPerMonth+" ((wattPerHour * 30) / 1000)");
                        billPerMonth = kiloWattPerMonth * costPerMonth;//estimated bill per month

                        Log.d("batelec", "bill per month: "+billPerMonth+" (kiloWattPerMonth * costPerMonth)");

                        Double res;
                        DecimalFormat df = new DecimalFormat("#.##");
                        res = Double.valueOf(df.format(billPerMonth));

                        Log.d("batelec", "new bill: "+res);

                        lblBillVal.setText(String.valueOf(res));
                        totalHour++;
                    }
                }catch(Exception e){
                    Log.d("batelec", ""+e);
                }
            }
            handler.postDelayed(runnable, delay);
        }
    };

}

这是我的自定义适配器代码:

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Switch;
import android.widget.TextView;

public class CustomCursorAdapter extends CursorAdapter {
    int wattTotal = 0;
    int pos, i;
    int[] tags;
    //components
    TextView txtDevName, txtDevWatt;
    Switch swiStatus;
    //ViewHolder viewHolder;
    @SuppressWarnings("deprecation")
    public CustomCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View retView = inflater.inflate(R.layout.list_view_design, parent, false);

        return retView;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        txtDevName = (TextView) view.findViewById(R.id.textDeviceName);
        txtDevName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
        String name = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1)));

        txtDevWatt = (TextView) view.findViewById(R.id.textDeviceWatt);
        txtDevWatt.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));

        swiStatus = (Switch) view.findViewById(R.id.switch1);
        int stat = cursor.getInt(cursor.getColumnIndex(cursor.getColumnName(3)));

        Log.d("batelec", "Name: "+ name + " Stat: "+stat);
        //Log.d("batelec", "tags: "+i);
       /* swiStatus.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.d("batelec", "switch click: "+i);
                ListViewForm lvf = new ListViewForm();
                lvf.itemClick();
            }

        });*/

        if (stat == 0){
            swiStatus.setChecked(false);
        }
        else{
            swiStatus.setChecked(true);
        }
        //i++;


    }
}

1 个答案:

答案 0 :(得分:0)

这是我的xml,我不明白yshahak最初的含义

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

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.03" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.03" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.03"
                android:text="@string/txtDeviceName"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.03"
                android:text="@string/txtDeviceWatt"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.03"
                android:gravity="top|end"
                android:text="@string/txtStatus"
                android:textAppearance="?android:attr/textAppearanceLarge" />
        </TableRow>

    </TableLayout>

    <ListView
        android:id="@+id/list_data"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:clickable="true"
        android:focusable="false"
        android:longClickable="true"
        android:descendantFocusability="blocksDescendants"/>

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.03" >

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/lblApproxBill"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/txtEstimateBill"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/lblBillValue"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:text="@string/txtNull"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:width="@dimen/listNameFieldSize" />

        </TableRow>
    </TableLayout>

</LinearLayout>