以编程方式更改ImageView上的边距 - Android

时间:2014-04-10 16:21:45

标签: android imageview android-alertdialog margins

我正在使用两个ImageViews lika按钮创建AlertDialog,但我不知道如何设置第一个ImageView的右边距,因为我想在它们之间留出空间。我的代码:

        Context context = Main.this;

        AlertDialog.Builder alert = new AlertDialog.Builder(context);

        // Layoutot
        LinearLayout layout = new LinearLayout(context);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,   // width
                                                LayoutParams.WRAP_CONTENT)); // height

        // Image Edit
        ImageView Edit = new ImageView(context);
        Edit.setImageResource(R.drawable.edit);
        Edit.setBackgroundResource(R.drawable.button);
        Edit.setPadding(5, 20, 5, 20);
        Edit.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, // width
                                                          LayoutParams.WRAP_CONTENT, // height
                                                          1f));                      // weight

        // Image Delete
        ImageView Delete = new ImageView(context);
        Delete.setImageResource(R.drawable.delete);
        Delete.setBackgroundResource(R.drawable.button);
        Delete.setPadding(5, 20, 5, 20);
        Delete.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, // width
                                                          LayoutParams.WRAP_CONTENT,   // height
                                                          1f));                        // weight

        layout.addView(Edit);
        layout.addView(Delete);
        alert.setView(layout);

        alert.show();

我尝试过类似的东西,但我只显示第一个(编辑)按钮

        LinearLayout.LayoutParams margins = new
        LinearLayout.LayoutParams(Edit.getLayoutParams());
        margins.setMargins(0, 0, 15, 0);
        Edit.setLayoutParams(margins);

1 个答案:

答案 0 :(得分:2)

您可以使用rightMargin ......

LinearLayout.LayoutParams margins = new LinearLayout.LayoutParams(Edit.getLayoutParams());
margins.rightMargin = 15;
Edit.setLayoutParams(margins);