我试图动态地将布局添加到MainActivity(Android Studio创建的默认Android应用程序)中,但是没有显示新的布局。 我尝试过不同的布局,但是在高度约为450px之后,它被裁剪了。
我对Android UI编程很陌生,我觉得我在添加功能方面做错了。这是添加代码(灵感来自this answer):
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linlayout);
View v = vi.inflate(R.layout.test_layout, null);
// insert into main view
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
1000,//ViewGroup.LayoutParams.FILL_PARENT,
1000);//ViewGroup.LayoutParams.FILL_PARENT);
linearLayout.addView(v, 0, layoutParams);
这是activity_main.xml:
<include
android:id="@+id/include"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
<LinearLayout
android:id="@+id/linlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!--<include layout="@layout/test_layout"/>-->
</LinearLayout>
这是我试图添加的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="@+id/imageView2"
android:layout_width="188dp"
android:layout_height="191dp"
app:srcCompat="@mipmap/ic_launcher" />
</RelativeLayout>
如果我静态添加布局(在xml中添加<include layout="@layout/test_layout"/>
),则test_layout
会正确显示。
我在这里做错了什么?
(在Nexus 5X上使用Android 7.1.2)
答案 0 :(得分:1)
使用此方法动态添加视图:
LinearLayout myLayout = (LinearLayout)findViewById(R.id.linlayout);
View testlin= getLayoutInflater().inflate(R.layout.test_layout, myLayout, false);
myLayout.addView(testlin);
答案 1 :(得分:0)
ll_fovorite = (LinearLayout) view.findViewById(R.id.ll_fovorite);
tv_no_fovorite = new TextView(getActivity());
tv_no_fovorite.setText("There are no fovorite words");
tv_no_fovorite.setTextColor(Color.parseColor("#8b8682"));
tv_no_fovorite.setTextSize(24);
tv_no_fovorite.setGravity(Gravity.CENTER);
tv_no_fovorite.setTypeface(Typeface.MONOSPACE);
ll_fovorite.addView(tv_no_fovorite, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);