LinearLayout 无法在某些设备上添加视图
LinearLayout unable to add view on some devices
我想向 LinearLayout 添加一些视图(主要是 TextView),但它仅适用于某些设备。我已经在 Samsung Galaxy S5、Lenovo Tab2 和 Samsung Galaxy S9 上测试了这段代码。只有 S5 使用此代码,它可以将视图添加到 LinearLayout。其他的不能加。这些代码有什么问题? xml 代码有问题吗?
提前致谢
Java代码:
lay.addView(getContentView(this, "Hello", Color.RED));
,,,
,,,
public TextView getContentView(Context mContext, String str, int color) {
Calendar calendar = Calendar.getInstance();
int h = calendar.get(Calendar.HOUR_OF_DAY);
int m = calendar.get(Calendar.MINUTE);
int s = calendar.get(Calendar.SECOND);
String time = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
TextView textView = new TextView(mContext);
textView.setText(time + " " + str);
textView.setTextColor(color);
return textView;
}
xml代码:
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:paddingBottom="8dp">
<LinearLayout
android:id="@+id/layContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:orientation="vertical"
android:paddingBottom="12dp">
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
您需要将布局参数设置为您创建的文本视图
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
我想向 LinearLayout 添加一些视图(主要是 TextView),但它仅适用于某些设备。我已经在 Samsung Galaxy S5、Lenovo Tab2 和 Samsung Galaxy S9 上测试了这段代码。只有 S5 使用此代码,它可以将视图添加到 LinearLayout。其他的不能加。这些代码有什么问题? xml 代码有问题吗?
提前致谢
Java代码:
lay.addView(getContentView(this, "Hello", Color.RED));
,,,
,,,
public TextView getContentView(Context mContext, String str, int color) {
Calendar calendar = Calendar.getInstance();
int h = calendar.get(Calendar.HOUR_OF_DAY);
int m = calendar.get(Calendar.MINUTE);
int s = calendar.get(Calendar.SECOND);
String time = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
TextView textView = new TextView(mContext);
textView.setText(time + " " + str);
textView.setTextColor(color);
return textView;
}
xml代码:
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:paddingBottom="8dp">
<LinearLayout
android:id="@+id/layContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:orientation="vertical"
android:paddingBottom="12dp">
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
您需要将布局参数设置为您创建的文本视图
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));