我已经创建了一个动态创建50个按钮的Android应用程序,它完美地工作,但问题是当我使用下面给出的代码动态地为这些按钮添加一些背景颜色时,我的视图会变坏。
buttons[i][j].setTextColor(Color.BLACK);
buttons[i][j].setBackgroundColor(Color.GREEN);
我的代码如下所示,任何人都可以告诉我一些解决方案
我的 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.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
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.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(35);
buttons[i][j].setWidth(75);
buttons[i][j].setTextColor(Color.BLACK);
buttons[i][j].setBackgroundColor(Color.GREEN);
tab++;
rowLayout.addView(buttons[i][j],param);
}
}
}
}
答案 0 :(得分:0)
你应该添加一些余量,让这些按钮留有一些喘息空间。
// First try with WRAP_CONTENT
LinearLayout.LayoutParams paramForButtons = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
// If the buttons look too small using WRAP_CONTENT, change to MATCH_PARENT
// Set the margins in this case
LinearLayout.LayoutParams paramForButtons = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
paramForButtons.setMargins(10, 10, 10, 10);
将for
循环的最后一行替换为:
rowLayout.addView(buttons[i][j],paramForButtons);