我正在尝试引用xml文件,以便在Android studio中动态添加TextView。我试图创建一个RelativeLayout对象并将TextView添加到该对象。我试图给RelativeView xml块一个id和引用。两次都没有出现。对我做错了什么的猜测?
这是我的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rl = new RelativeLayout(this);
firstNumber = (TextView) findViewById(R.id.numberOne);
firstNumber.setText(String.valueOf(myAddition.getNumOne()));
secondNumber = (TextView) findViewById(R.id.numberTwo);
secondNumber.setText(String.valueOf(myAddition.getNumTwo()));
brandNew = new TextView(this);
brandNew.setText("Hello");
rl.addView(brandNew);
}
这是xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Math Champ"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="87"
android:id="@+id/numberOne"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="21"
android:id="@+id/numberTwo"
android:layout_below="@+id/numberOne"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/default_answer"
android:id="@+id/answer"
android:layout_below="@+id/numberTwo"
android:layout_centerHorizontal="true" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
android:layout_centerHorizontal="true"
android:layout_below="@+id/answer"/>
</RelativeLayout>
答案 0 :(得分:2)
不要创建新的RelativeLayout。使用类似的东西来获取对已经在XML中创建的RelativeLayout的引用:
RelativeLayout rl = (RelativeLayout )findViewById(R.id.relativeLayoutId);
请注意,
R.id.relativeLayoutId
将是您在XML中指定为id的任何内容。例如:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayoutId">