在Android中获取切换按钮的状态

时间:2016-05-02 20:50:10

标签: android android-layout listview togglebutton android-togglebutton

我正在尝试创建一个列表视图,其中每个项目都有两个东西,textview中的描述和切换按钮。 textview中的详细信息由AsyncTask动态加载。在listview的末尾,我以编程方式插入了一个按钮。单击该按钮时,我需要获取所有文本视图中的数据以及所有ToggleButtons的状态。这是我使用的代码:

XML文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dfdede"
android:focusable="true"
android:focusableInTouchMode="false">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="15dp"
    android:textColor="#000000"
    android:textSize="20dp" />

<ToggleButton
    android:id="@+id/toggle1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:checked="true"
    android:text="ToggleButton" />

<View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_alignBottom="@id/textView1"
    android:background="#49656565" />

public class MarkAttendance extends ListActivity {

String url = "http://192.168.173.1:8080/WebApplication1/androidrollsheet.jsp";
String pid = "";
ArrayList<String> array = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pid = getIntent().getStringExtra("pid");
    new LoadRollSheet().execute();

    final ListView lv = getListView();
    Button submitButton = new Button(this);
    submitButton.setText("Submit");
    lv.addFooterView(submitButton);

    submitButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ListAdapter adapter = lv.getAdapter();
            int total = adapter.getCount() - 1;
            for (int i = 0; i < total; i++) {
                View rowview = adapter.getView(i, null, lv);
                TextView textView = (TextView) rowview.findViewById(R.id.textView1);
                ToggleButton toggle1 = (ToggleButton) rowview.findViewById(R.id.toggle1);
                String studentDetails = textView.getText().toString();
                String value = String.valueOf(toggle1.getText());
                Log.i("VALUE ???? ", value);
            }
        }
    });
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_mark_attendance, menu);
    return true;
}

private ProgressDialog pDialog;

class LoadRollSheet extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MarkAttendance.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("pid", pid));
        // getting JSON string from URL
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);
        // Check your log cat for JSON reponse
        Log.d("All Entries: ", json.toString());
        //getting Sections array from JSON object
        JSONArray rollSheet = null;
        try {
            rollSheet = json.getJSONArray("RollSheet");
            //looping through all sections
            for (int i = 0; i < rollSheet.length(); i++) {
                JSONObject entry = rollSheet.getJSONObject(i);
                int rollNo = entry.getInt("rollNo");
                int userId = entry.getInt("userId");
                String studentName = entry.getString("studentName");

                String value = rollNo + "  " + studentName;
                array.add(value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_mark_attendance, R.id.textView1, array);
                setListAdapter(adapter);
                ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
            }
        });
    }
}

}

但是,问题在于我能够在文本视图中正确获取String,而不是切换按钮的状态。在这种情况下,它总是成为ON的默认状态。对此的任何帮助都会非常好:(

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题;

final Boolean toggleState = toggle1.isChecked();

答案 1 :(得分:0)

我相信你可以使用isChecked(),不是吗?

编辑:另一次尝试,这是否有效(?):

ToggleButton toggle = (ToggleButton)findViewById(R.id.toggle);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.e(TAG, String.valueOf(isChecked));
    }
});