以编程方式构建自定义卡视图

时间:2016-03-16 10:28:59

标签: android layout view textview android-cardview

我遇到了以编程方式创建自定义视图的问题。

我写了类似的东西:

public class TimerCardView extends CardView {
    private LinearLayout horizontalContentLayout;
    private TextView timeTextView;


    public TimerCardView(Context context, AttributeSet attrs) {
        super(context, attrs);

        horizontalContentLayout = new LinearLayout(context);
        LinearLayout.LayoutParams horizontalContentXLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        horizontalContentXLayoutParams.gravity = Gravity.CENTER;
        horizontalContentLayout.setLayoutParams(horizontalContentXLayoutParams);

        this.addView(horizontalContentLayout);

        timeTextView = new TextView(context);
        timeTextView.setTextColor(Color.parseColor("#A3A3A3"));
        timeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
        timeTextView.setText("0:00:00");

        this.horizontalContentLayout.addView(timeTextView);
    }
}

在xml中我添加了:

<com.example.paciu.belmondo.ViewsExtends.TimerCardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardCornerRadius="2dp"
    card_view:cardElevation="2dp"
    android:layout_margin="4dp">
</com.example.paciu.belmondo.ViewsExtends.TimerCardView>

问题是我的文本视图不在布局的屏幕中心。它仍然留在左边。但是当我首先向xml添加相同的内容(但整个xml中):

<android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        card_view:cardCornerRadius="2dp"
        card_view:cardElevation="2dp"
        android:layout_margin="4dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="40sp"
                android:text="sdasdasd"
                android:textColor="#AAAAAA" />

        </LinearLayout>

</android.support.v7.widget.CardView>

我做错了什么?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

CardView扩展了FrameLayout类。 layout_gravity属性位于FrameLayout.LayoutParams,而非{strong> horizo​​ntalContentLayout 。要像在XML中那样设置重力,请使用以下内容:

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.CENTER);
    this.addView(horizontalContentLayout,params);