通过OnClickListener访问Button的LinearLayout

时间:2014-11-12 00:44:43

标签: android button android-linearlayout onclicklistener

我在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?

1 个答案:

答案 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
        }

    }
});