我正在尝试动态地向LinearLayout添加一个按钮。这是我的代码:
JAVA
LayoutInflater inflater = mMainActivity.getLayoutInflater();
View layout = inflater.inflate(R.layout.browse_list_fragment, (ViewGroup) getView(), false);
LinearLayout breadcrumb = (LinearLayout) layout.findViewById(R.id.browse_list_fragment_previous);
Button button = new Button(mMainActivity);
button.setText(name);
button.setTextColor(mMainActivity.getResources().getColor(R.color.action_bar_breadcrumb));
button.setTextSize(22);
button.setTypeface(Typeface.createFromAsset(mMainActivity.getAssets(), "HelveticaNeueBold.ttf"));
button.setTag(mHashMap);
breadcrumb.addView(button, new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
的 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:id="@+id/browse_list_fragment_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/white">
<Button android:id="@+id/browse_list_fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="@string/button_menu"
android:textColor="@color/grey"
android:background="@android:color/transparent"
android:drawableLeft="@drawable/carrot_grey"
android:onClick="buttonClick"/>
</LinearLayout>
<LinearLayout android:id="@+id/browse_list_fragment_previous"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical">
</LinearLayout>
<ListView android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingLeft="5dp"/>
</LinearLayout>
问题
我没有抛出任何异常,当我连接调试器并逐步执行代码时,我可以看到按钮实际上已添加到布局中。我尝试过膨胀按钮并添加它,Java和XML代码的不同组合,删除代码行,使用RelativeLayout作为根布局,删除布局的不同部分并使用不同的宽度和高度但是我不能这样做按钮显示在屏幕上。有人可以看到我做错了什么或者至少指出了我正确的方向吗?我非常感激。
答案 0 :(得分:2)
您使用inflater.inflate()
作为最后一个参数调用false
:
View layout = inflater.inflate(R.layout.browse_list_fragment,
(ViewGroup) getView(), false);
因此,您不会将布局添加到任何视图,因此无法看到您添加到此布局的按钮。尝试使用inflate()
致电true
或稍后将视图添加到视图中。