繁体   English   中英

以编程方式无法在RelativeLayout中对齐ImageView

[英]Programmatically Can't Align ImageView in RelativeLayout

我无法将imageview添加到相对布局中。 我想将图像添加到我使用RelativeLayout动态创建的菜单项列表中。 我的所有菜单项都显示正常并且按顺序排列但是当我尝试为每个项目添加图像时,我只得到一个箭头并且它不是垂直居中的。 以下是我的代码。

在我的XML文件中

<RelativeLayout 
            android:id="@+id/pMenu"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </RelativeLayout>

在我的代码中:

private void buildMenu(String name, int id) {

    String[] menuItems = getResources().getStringArray(pMenus[id]);
    // Get the rel layout from xml
    RelativeLayout container = (RelativeLayout) findViewById(R.id.pMenu);

    int imageId=1;
    Typeface tf = Typeface.createFromAsset(this.getAssets(),"mreavesmodot-reg.otf");
    for(String menuItem: menuItems) {           

        // Defining the layout parameters
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);


        StyledButton menuImage = new StyledButton(this);
        menuImage.setBackgroundResource(R.drawable.menu_button);
        menuImage.setText(menuItem);
        menuImage.setTypeface(tf);
        menuImage.setTextSize(19);
        menuImage.setPadding(20, 0, 0, 0);
        menuImage.setTextColor(Color.WHITE);
        menuImage.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        menuImage.setOnClickListener(getOnClickListener(menuImage, name));
        menuImage.setId(imageId);

        if(imageId==1) {
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        } else {
            lp.addRule(RelativeLayout.BELOW ,imageId-1);
        }
        menuImage.setLayoutParams(lp);


        ImageView arrow = new ImageView(this);
        arrow.setImageResource(R.drawable.arrow_menu);
        arrow.setPadding(0, 0, 15, 0);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, 
                RelativeLayout.LayoutParams.WRAP_CONTENT );
        params.addRule(RelativeLayout.ALIGN_RIGHT,menuImage.getId());
        params.addRule(RelativeLayout.CENTER_VERTICAL);

        arrow.setLayoutParams(params);

        container.addView(menuImage);
        container.addView(arrow);

        imageId++;
    }
}

我认为下面这行是你的问题

params.addRule(RelativeLayout.CENTER_VERTICAL); 

是的,您最有可能添加多个箭头,它们只是一个在彼此之上,所有这些都与完整相对布局的垂直中心对齐。 该命令不会对您的按钮项执行垂直居中,而是对父亲RelativeLayout执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM