Sunday 16 February 2014

Android Dynamic Check-box Example

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Attendance extends Activity {
CheckBox checkBox;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stud_attendence);
LinearLayout my_layout = (LinearLayout) findViewById(R.id.my_layout);
LinkedHashMap<String, String> alphabet = new LinkedHashMap<String, String>();
// int Array_Count = 0;
String[] Str_Array = new String[] { "12111447:Arun Kumar",
"12111448:Aneesh", "12111449:Binoy shyam" };


for (int i = 0; i < Str_Array.length; i++) {
String[] std= Str_Array[i].split(":");
alphabet.put(std[0],std[1]);

}

Set<?> set = alphabet.entrySet();

Iterator<?> i = set.iterator();
while (i.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry me = (Map.Entry) i.next();
checkBox = new CheckBox(this);
checkBox.setId(Integer.parseInt(me.getKey().toString()));
checkBox.setText(me.getKey().toString()+" : "+me.getValue().toString());
checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
my_layout.addView(checkBox);
}

}

View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(
getApplicationContext(),
"Id:" + button.getId() + " and text: "
+ button.getText().toString(), 2000).show();

}
};
}

}

Output:





No comments:

Post a Comment