2014-03-06 89 views
0

我正在开发Android API v11。有一个很大的RelativeLayout区域(像一个画布),应该用编程方式填充一些按钮。每个按钮代表一个视频,我用VideoViewButton扩展了android.widget.Button类。以编程方式在旁边添加一个按钮

这里是我的主要活动现在在做什么:

private void addButtonForVideo(int videoId) { 
    Log.d(TAG, "Adding button for video " + videoId); 
    VideoButtonView button = new VideoButtonView(this, videoId); 
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_napping); 

    layout.addView(button, params); 
    mVideoButtons.add(button); 
} 

这里,mVideoButtons只是包含了所有的按钮,所以我可以在以后引用它们。

然而,按钮本身放置在RelativeLayout的左上角,一个在另一个之上。我需要做的是将每个按钮放在前一个的右侧,因此它们填满屏幕。

我试过了,我检查视频ID是不是0(意思是,一个按钮已经存在)。然后我得到先前放置的按钮的ID,并说,我想下一个按钮放置正确的前一个:

private void addButtonForVideo(int videoId) { 
    Log.d(TAG, "Adding button for video " + videoId); 
    VideoButtonView button = new VideoButtonView(this, videoId); 
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_napping); 

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
      ViewGroup.LayoutParams.WRAP_CONTENT, 
      ViewGroup.LayoutParams.WRAP_CONTENT 
    ); 

    // align to right of previous button 
    if (videoId != 0) { 
     VideoButtonView previousButton = mVideoButtons.get(videoId - 1); 
     params.addRule(RelativeLayout.RIGHT_OF, previousButton.getId()); 
    } 

    layout.addView(button, params); 
    mVideoButtons.add(button); 
} 

但是,它不工作 - 按键仍然被置于彼此的顶部。我如何让他们在前一个旁边展示?

+0

你可以显示你调用'setId'的'VideoButtonView'的构造函数吗?那么'mVideoButtons'的类型是什么? – Rajesh

+0

@Rajesh Gotcha,我从来没有在构造函数中调用'setId'。从来没有想到这是必要的。你能把它作为答案发布吗? – slhck

+0

按要求完成。 – Rajesh

回答

1

您需要在VideoButtonView的构造函数中调用setId并使用videoId才能正常工作。

确保setId包含一个正数,因此,例如,如果videoId s的0,使用启动:

public VideoButtonView(Context context, int videoId) { 
    super(context); 
    this.setId(videoId + 1); 
    // other code to set layout 
} 
+0

以'0'作为ID时,它并不适用于我,但每个正数都可以在这里使用。我修改了你的答案以包含这一点。谢谢你的帮助。 – slhck

+0

是的,0不是有效的标识符。 – Rajesh

0

我建议不要使用相对布局放置对象编程。使用线性布局,而不是使用LinearLayout.LayoutParams

组织内容要与LinearLayout中做到这一点,只要确定你的方向设置为水平

private void addButtonForVideo(int videoId) { 
Log.d(TAG, "Adding button for video " + videoId); 
VideoButtonView button = new VideoButtonView(this, videoId); 
LinearLayout layout = (LinearLayout) findViewById(R.id.layout_napping); 

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCHPARENT, 
     LinearLayout.LayoutParams.WRAP_CONTENT, 
); 

LinearLayout buttonWrapper = new LinearLayout(); 
buttonWrapper.setLayoutParams(params); 
buttonWrapper.setOrientation(LinearLayout.HORIZONTAL); 

// align to right of previous button 
if (videoId != 0) { 
    VideoButtonView previousButton = mVideoButtons.get(videoId - 1); 
} 

buttonWrapper.addView(button); 
layout.addView(buttonWrapper); 
mVideoButtons.add(button); 

}

记得刚放置的第一个按钮在ButtonWrapper中放置第二个之前。

使用线性布局,下一个孩子将显示在下方或旁边的前一个孩子,具体取决于布局的方向和方向。在这里,每个按钮将彼此相邻并且包装将延伸它所处的布局的全部长度。

祝你好运!

+0

这可能工作,但我知道由于某种原因,我不能在这个特定的上下文中使用LinearLayout。 – slhck

相关问题