我想在当前视图中以编程方式添加TextView。我知道如何在创建新布局时创建它,但我想将其添加到当前布局,主要问题是如何获取对main_activity布局的引用。
感谢您的回答。
答案 0 :(得分:1)
我们假设您的项目中有LinearLayout
,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/main"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
要在布局中添加许多TextView's
,您可以执行以下操作:
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View linearLayout = findViewById(R.id.main);
TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(valueTV);
}
}
答案 1 :(得分:0)
RangeValidator1.MinimumValue = 0;
RangeValidator1.MaximumValue = 10;
RangeValidator1.Type = ValidationDataType.Integer;
RangeValidator1.Validate();
if (!RangeValidator1.IsValid)
{
if(Convert.ToInt32(text1.Text) < 0)
{
RangeValidator1.ErrorMessage = "number can not be less than 0";
}
else
{
RangeValidator1.ErrorMessage = "number can't be above maxvalue";
}
}