我想以编程方式重新创建XML布局,但它似乎不起作用。我发现了如何(据说)从另一个线程以编程方式创建它。任何帮助表示赞赏,谢谢。
XML:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="@android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test1"
android:id="@+id/txt1"
android:paddingTop = "36dp"
android:paddingRight = "36dp"
android:paddingLeft = "18dp"
android:paddingBottom = "36dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test2"
android:layout_toRightOf="@id/txt1"
android:id="@+id/txt2"
android:paddingTop = "36dp"
android:paddingRight = "36dp"
android:paddingBottom = "36dp"/>
</RelativeLayout>
以下是我尝试匹配上述XML的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
// Creating a new TextView
TextView txt1 = new TextView(this);
txt1.setText("Test1");
TextView txt2 = new TextView(this);
txt2.setText("Test2");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.RIGHT_OF, txt1.getId());
txt1.setPadding(18,36,36,36);
txt2.setPadding(0,36,36,36);
// Setting the parameters on the TextView
txt1.setLayoutParams(lp);
txt2.setLayoutParams(lp2);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(txt1);
relativeLayout.addView(txt2);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}