在android中为按钮制作按压效果

时间:2013-07-21 05:07:55

标签: android button

我已经创建了一个动态创建50个按钮的Android应用程序,它完美地运行,但问题是当我为这些按钮动态设置一些背景颜色时,按钮的按压效果会丢失

任何人都可以告诉我一些解决方案,以保持按钮单击的按压效果 我的代码如下所示 我的 Android平台是2.3.3

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class MyMain extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mymain);
        createCalender();
    }
   public void createCalender()
   {  
    LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, 1.0f);


    param.setMargins(10, 10, 10, 10);


    LinearLayout rowLayout=null;
    Button[][] buttons = new Button[10][5]; 
    int count=51;
    int tab=1;
    for (int i = 0; i<10; i++) 
    {
        if(count%5==1)
        {
            rowLayout = new LinearLayout(this);
            rowLayout.setBackgroundColor(Color.BLACK);
            rowLayout.setWeightSum(5);
            layoutVertical.addView(rowLayout,param);
            count=count-5;
        }
        for(int j=0;j<5;j++)
        {
            buttons[i][j]=new Button(this);
            buttons[i][j].setText(""+tab);
            buttons[i][j].setHeight(55);
            buttons[i][j].setWidth(80);
            buttons[i][j].setTextColor(Color.BLACK);
            buttons[i][j].setBackgroundColor(Color.GREEN);

            tab++;

            rowLayout.addView(buttons[i][j],param);

        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

buttons[i][j].setBackgroundColor(Color.GREEN);之后

buttons[i][j].setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        v.setBackgroundColor(Color.GRAY); // Choose whichever color

        new Handler().postDelayed(new Runnable() {

            public void run() {

                v.setBackgroundColor(Color.GREEN);

                // Button Click Code Here
            }

        }, 100L);    // Change this value to whatever is suitable

    }

});