在 LinearLayout 中设置 View 的属性

Setting properties of View in LinearLayout

我想为 Android 视图设置以下属性,但在代码中。

这是我要复制的 AdView:

<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#000000"
android:paddingTop="5dp"
app:adSize="SMART_BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111"/>

这是我目前的代码:

mAdView = new AdView(m_Context);
// Sizes BANNER, SMART_BANNER, LARGE_BANNER
mAdView.setAdSize(AdSize.SMART_BANNER);
//mAdView.setAdUnitId(adIdBanner);
mAdView.setBackgroundColor(0xFF000000); // First byte alpha
mAdView.setPadding(0, 5, 0, 0);
lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
mAdView.setLayoutParams(lp);
myLayout.addView(mAdView);
// OR SHOULD IT BE THIS????
//LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                            ViewGroup.LayoutParams.MATCH_PARENT,
//                            ViewGroup.LayoutParams.MATCH_PARENT);
//myLayout.addView(mAdView, params);

这是正确的吗?

CenterInParent 怎么样?

我是否正确设置了宽度和高度,以便宽度为 matchparent,高度为 wrapcontent?

试试这个:

int paddingTop = 5;
float density = m_Context.getResources().getDisplayMetrics().density
int padding = (int)(paddingTop * density);


mAdView = new AdView(m_Context);
// Sizes BANNER, SMART_BANNER, LARGE_BANNER
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId(adIdBanner);
mAdView.setBackgroundColor(Color.parseColor("#000000")); 
mAdView.setPadding(0, padding , 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mAdView.setLayoutParams(params);
myLayout.addView(mAdView);