android添加按钮出错,Button bn = new Button(this);报错
publicclassMainActivityextendsActivity{GridLayoutgridLayout;Buttonbn_add;intlocation=...
public class MainActivity extends Activity
{
GridLayout gridLayout;
Button bn_add;
int location = 0;
String[] chars = new String[]
{
"1", "2", "3",
"4", "5", "6",
"7", "8"
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.root);
bn_add = (Button) findViewById(R.id.add);
bn_add.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source) {
Button bn = new Button(this);//这句报错
location++;
bn.setText(chars[location-1]);
bn.setPadding(10, 5, 0, 0);
GridLayout.Spec rowSpec = GridLayout.spec(location / 3 );
GridLayout.Spec columnSpec = GridLayout.spec(location % 3);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridLayout.addView(bn_add, params);
}
});
}
} 展开
{
GridLayout gridLayout;
Button bn_add;
int location = 0;
String[] chars = new String[]
{
"1", "2", "3",
"4", "5", "6",
"7", "8"
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.root);
bn_add = (Button) findViewById(R.id.add);
bn_add.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source) {
Button bn = new Button(this);//这句报错
location++;
bn.setText(chars[location-1]);
bn.setPadding(10, 5, 0, 0);
GridLayout.Spec rowSpec = GridLayout.spec(location / 3 );
GridLayout.Spec columnSpec = GridLayout.spec(location % 3);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridLayout.addView(bn_add, params);
}
});
}
} 展开
展开全部
把this换成MainActivity.this,因为你是在匿名内部类使用this,你的this是指OnClickListener
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
this改成MainActivity.this
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
this改成MainActivity.this
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询