我有一个对话框片段,其布局中定义了一个EditText,并且以编程方式添加了许多其他EditTexts(因为它们的编号可能会有所不同)。我的问题是xml中定义的那个具有默认的平台样式 - 例如下面的蓝色条 - 而以编程方式添加的条似乎没有样式。请参见屏幕截图以供参考。
如何在保持默认样式的同时以编程方式创建EditText?
我如何创建EditTexts:
EditText et = new EditText(this.getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.topMargin = 10;
et.setText("whatever");
et.setLayoutParams(params);
mContainer.addView(et);
答案 0 :(得分:3)
首先在Layout文件夹中创建xml资源,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is a template"
style="@style/my_style" />
然后在你的代码中将其膨胀如下:
TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
希望这有效。
答案 1 :(得分:1)
使用以下代码段。
EditText et = new AppCompatEditText(this.getActivity());
答案 2 :(得分:0)
使用以下代码段
Drawable drawable = editText.getBackground();
int sdk = android.os.Build.VERSION.SDK_INT;
int osVersion = android.os.Build.VERSION_CODES.JELLY_BEAN;
if(sdk < osVersion) {
editText.setBackgroundDrawable(originalDrawable);
} else {
editText.setBackground(originalDrawable);
}