我在Buttons
中有一些LinearLayout
。两者都是动态创建的。有没有办法通过LinearLayout
访问Button
?我将LinearLayouts
id's
设置为0或1.所以我只希望按钮在LinearLayout
等于1时执行某些操作。
代码:
LinearLayout linearLayout = new LinearLayout(view.getContext());
linearLayout.setId(1);
Button dynamicButtons = new Button(view.getContext());
...
...
...
linearLayout.addView(dynamicButtons, layoutParam);
现在我将Button
添加到LinearLayout
。我可以为Button's
OnClickListener
:
dynamicButtons.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
if (dynamicButton.getParentView().getId()==1){ //When I click the Button, I want to access the LinearLayout the Button is in
//do something
}
}
});
当然这一行dynamicButton.getParentView().getId()==1
是错误的。但是,我如何访问Button's
LinearLayout?
答案 0 :(得分:2)
你走在正确的轨道上。您需要做的就是转换为线性布局。
dynamicButtons.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
LinearLayout ll = (LinearLayout) dynamicButtons.getParent();
if (ll.getId()==1){ //When I click the Button, I want to access the LinearLayout the Button is in
//do something
}
}
});