我有一系列按钮。现在,当单击每个按钮时,我希望按钮文本显示在textBox中。我尝试了但它不起作用。这是我的代码:
public boolean initDay()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1);
for (i = 0; i<6; i++)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout,param);
for(j=0;j<7;j++)
{
pBtnDay[i][j]=new Button(this);
rowLayout.addView(pBtnDay[i][j],param);
pBtnDay[i][j].setClickable(true);
pBtnDay[i][j].setOnClickListener(this);
}
}
return true;
}
public void onClick(View v)
{
TextView t = (TextView)findViewById(R.id.textV);
t.setText(pBtnDay[i][j].getText());
}
答案 0 :(得分:2)
您应该将t.setText(pBtnDay[i][j].getText());
更改为t.setText(v.getText());
变量i
并且j
在onClick
方法中不可见,并且它们在那里都等于0。
答案 1 :(得分:0)
public boolean initDay()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1);
for (i = 0; i<6; i++)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout,param);
for(j=0;j<7;j++)
{
pBtnDay[i][j]=new Button(this);
rowLayout.addView(pBtnDay[i][j],param);
pBtnDay[i][j].setClickable(true);
pBtnDay[i][j].setOnClickListener({
public void onClick(View v){
TextView t = (TextView)findViewById(R.id.textV);
t.setText(view.getText());
});
}
}
return true;
}
答案 2 :(得分:0)
public boolean initDay()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
Button pBtnDay;
LayoutParams param = new
TextView t = (TextView)findViewById(R.id.textV);
LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1);
for (i = 0; i<6; i++)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout,param);
for(j=0;j<7;j++)
{
pBtnDay=new Button(this);
rowLayout.addView(pBtnDay,param);
pBtnDay.setClickable(true);
}
}
return true;
}
pBtnDay.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
t.setText(v.getText());
}
});