【发布时间】:2023-03-27 21:56:02
【问题描述】:
我想从我的 res/layout 目录中扩充一个布局,并在我的活动类中添加一些视图。
我的布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_marginTop="30dip"
android:layout_height="fill_parent" >
<Button
android:id="@+id/reg_button"
style="@style/simple_button"
android:onClick="clickButton"
android:text="@string/reg_button" />
<!-- I WANT TO PUT CONTENT HERE ! -->
</LinearLayout>
在我的 java 代码中,我尝试扩展上述布局并添加一个带有 Button 的线性布局。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
//inflate xml
LinearLayout mainLayout = (LinearLayout) LayoutInflater.from(getBaseContext()).inflate(R.layout.regions_search, null);
//Create a new LinearLayout
LinearLayout newLinear = new LinearLayout(mContext);
newLinear.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//create a new Button
Button test = new Button(mContext);
test.setText("My button");
//first , I add button to the LinearLayout
newLinear.addView(test);
//Then, I add layout to the inflated layout
mainLayout.addView(newLinear);
//display
setContentView(mainLayout);
但是 newLinear 视图(及其子视图)没有显示出来。
【问题讨论】:
-
你想要什么?当你按下
click button然后显示My Button? -
我只想在调用活动时显示 MyButton。 (在某些情况下,我的按钮不会显示,这就是为什么我想在java端控制显示)
标签: android android-linearlayout layout-inflater