以编程方式在 LinearLayout 中将 CardView 居中

Centering CardView in LinearLayout programmatically

public void makeCard( Context context, View view, String time, String startpt1, String startpt2, String endpt1, String endpt2)
{
    CardView card = new CardView(context);
    LinearLayout ll = view.findViewById(R.id.rides);
    // Set the CardView layoutParams
    int w = getResources().getDimensionPixelSize(R.dimen._270sdp);
    int h = getResources().getDimensionPixelSize(R.dimen._120sdp);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(w, h);
    card.setForegroundGravity(17);
    card.setLayoutParams(params);


    card.setRadius(60);
    card.setCardElevation(60);

    Typeface latoregular = getResources().getFont(R.font.latoregular);
    Typeface latobold = getResources().getFont(R.font.latobold);
    // Initialize a new TextView to put in CardView

    TextView tv = new TextView(context);
    tv.setLayoutParams(params);
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    try {
        Date date = format.parse(time);
        tv.setText(date.toString());
        Log.d("ASD", String.valueOf(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    tv.setTextSize(14);
    tv.setPadding(60,40,0,0);
    tv.setTextColor(Color.parseColor("#1fb286"));
    tv.setTypeface(latobold);
    tv.setTypeface(tv.getTypeface(), Typeface.BOLD);
    card.addView(tv);
    ll.addView(card);
}

这张cardview紧贴着侧面,无论我怎么改变布局引力,卡片都不会移动。我可以设置左侧的填充使其看起来居中,但在不同尺寸的屏幕上它不会完全居中

您正在创建 RelativeLayout.LayoutParams 并将它们用于 LinearLayoutCardView(这是一种 FrameLayout)。这不太可能奏效。据我所知,应该使用例如LinearLayout.LayoutParams 对于要添加到 LinearLayoutView(经验法则:使用以父 ViewGroup 命名的 LayoutParams

为了使 CardView 居中,您必须以编程方式设置其 android:layout_gravity 属性:

int w = getResources().getDimensionPixelSize(R.dimen._270sdp);
int h = getResources().getDimensionPixelSize(R.dimen._120sdp);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(w, h);   
params.gravity = Gravity.CENTER;