开发者

Need to save variables for my onClick

for ( int i = 0; i < responses.size(); i++ )
    {
        Button btn = new Button( this );
        btn.setText( guideStep.getResponse( 开发者_C百科i ).getTitle() );
        btn.setOnClickListener(new OnClickListener() {
            public void onClick( View v )
            {
                try
                {
                    //NextStep(guideStep.getStep(), guideStep.getSession(), guideStep.getResponse( i ).getId() );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                }
            }
        });
        linearLayout.addView( btn );
    }

Looking at the following code. I am adding buttons dynamically to my linear layout. I need to, dynamically aswell, change the onClick event for each button. For that, I need the counter from the loop and some way to save my guideStep object, from without the loop aswell.

Is there any way to do this?


You can use the setTag(your_id) method on your button and then get the id back with getTag() method in your OnClick.


for ( int i = 0; i < responses.size(); i++ )
{
     final int id = i; // save your variable

     ...
     try
     {
       NextStep(guideStep.getStep(), guideStep.getSession(), 
            guideStep.getResponse( id ).getId() ); // use it
     }
     ....
}


for ( int i = 0; i < responses.size(); i++ )
{
    final int fin_i = i;
    ...
    btn.setOnClickListener(new OnClickListener() {
        public void onClick( View v )
        {
           // Use fin_i 
        });
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜