【发布时间】:2016-07-02 04:11:22
【问题描述】:
我在以编程方式创建自定义视图时遇到问题。
我写了类似的东西:
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>
我做错了什么?感谢您的帮助!
【问题讨论】:
-
我也试过了,但还是一样。那么为什么在第二个xml中没有那个就可以了?在第二个 xml 中,整个布局居中...为什么我的类代码居中不起作用?
-
horizontalContentLayout.addView(timeTextView, horizontalContentXLayoutParams)应该这样做 -
还是不行。
-
尝试使用
LayoutParams.MATCH_PARENT作为宽度而不是WRAP_CONTENT -
在水平布局和 timeTextView 中的 MATCH_PARENT 都可以工作。但是如果我想在布局中添加第二个 textview 怎么办?我不明白这是为什么?
标签: android layout view textview android-cardview