23

层次结构是这样的:

  • 相对布局
    • 线性布局(垂直)
      • 框架布局(权重 5)
        • 图像视图
      • 查看(重量 1)

视图只是一个用于间隔目的的虚拟视图。我在布局 xml 中做到了,它可以工作。但是当我想以编程方式进行时,以下代码不起作用。

LinearLayout LL = new LinearLayout(this);
ImageView ladder = new ImageView(this);
FrameLayout ladderFL = new FrameLayout(this);
View dummyView = new View(this);
ladder.setImageResource(R.drawable.ladder1);
LL.setOrientation(LinearLayout.VERTICAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams ladderFLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 0);
ladderFLParams.weight = 5f;
LinearLayout.LayoutParams dummyParams = new LinearLayout.LayoutParams(0,0);
dummyParams.weight = 1f;

FrameLayout.LayoutParams ladderParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
ladder.setLayoutParams(ladderParams);
ladderFL.setLayoutParams(ladderFLParams);
dummyView.setLayoutParams(dummyParams);
LL.setWeightSum(6f);
LL.setLayoutParams(LLParams);

ladderFL.addView(ladder);
LL.addView(ladderFL);
LL.addView(dummyView);
((RelativeLayout) findViewById(R.id.screenRL)).addView(LL);
4

1 回答 1

62
LinearLayout LL = new LinearLayout(this);
    LL.setBackgroundColor(Color.CYAN);
    LL.setOrientation(LinearLayout.VERTICAL);

    LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

    LL.setWeightSum(6f);
    LL.setLayoutParams(LLParams);


    ImageView ladder = new ImageView(this);
    ladder.setImageResource(R.drawable.ic_launcher);

    FrameLayout.LayoutParams ladderParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
    ladder.setLayoutParams(ladderParams);

    FrameLayout ladderFL = new FrameLayout(this);
    LinearLayout.LayoutParams ladderFLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 0);
    ladderFLParams.weight = 5f;
    ladderFL.setLayoutParams(ladderFLParams);       
    ladderFL.setBackgroundColor(Color.GREEN);
    View dummyView = new View(this);

    LinearLayout.LayoutParams dummyParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0);
    dummyParams.weight = 1f;
    dummyView.setLayoutParams(dummyParams);
    dummyView.setBackgroundColor(Color.RED);



    ladderFL.addView(ladder);
    LL.addView(ladderFL);
    LL.addView(dummyView);
    RelativeLayout rl=((RelativeLayout) findViewById(R.id.screenRL));
    rl.addView(LL);

我刚刚整理了你的代码以便更好地理解,还给它一个背景颜色以获得清晰的图片,因为我不知道你想要什么,你可以通过它。我希望它是有帮助的。您应该提供您的工作 xml,以便我们确切地知道您想要什么。

于 2013-09-28T10:32:49.067 回答