package com.ecs.wenchen.dynamiccheckbox;
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.TextView;
import android.widget.EditText;
import android.graphics.Color;
public class MainActivity extends Activity {
LinearLayout linearBox;
CheckBox checkBox, checkBox1;
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
linearBox = (LinearLayout) findViewById( R.id.linearBox );
final EditText number = (EditText) findViewById( R.id.number );
final EditText title = (EditText) findViewById( R.id.title );
final Button button = (Button) findViewById( R.id.add );
button.setOnClickListener( new View.OnClickListener( ) {
public void onClick( View v ) {
checkBox1 = new CheckBox( getApplicationContext( ) );
checkBox1.setId( Integer.parseInt( number.getText( ).toString( ) ) );
checkBox1.setText( title.getText( ).toString( ) );
checkBox1.setTextColor( Color.BLACK );
checkBox1.setOnClickListener( getOnClickDoSomething( checkBox1 ) );
linearBox.addView( checkBox1 );
}
} );
final LinkedHashMap<String, String>
alphabet = new LinkedHashMap<String, String>( );
alphabet.put( "260", ".NET" );
alphabet.put( "370", "Computer Architecture" );
Set<?> set = alphabet.entrySet( );
// Get an iterator.
Iterator<?> i = set.iterator( );
// Display elements.
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.getValue( ).toString( ) );
checkBox.setOnClickListener( getOnClickDoSomething( checkBox ) );
linearBox.addView( checkBox );
}
}
View.OnClickListener getOnClickDoSomething( final Button button ) {
return new View.OnClickListener( ) {
public void onClick( View v ) {
final TextView tvView = (TextView) findViewById( R.id.textView3 );
tvView.setText( button.getId( ) + ": " + button.getText( ).toString( ) );
}
};
}
}
|