如何动态扩充布局?

She*_*lam 5 java eclipse android android-layout layout-inflater

我在XML中定义了以下布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/streamRelativeLayout">
        <ListView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/streamListView"></ListView>
        <ProgressBar android:layout_centerInParent="true" android:layout_height="wrap_content" android:id="@+id/streamProgressBar" android:layout_width="wrap_content"></ProgressBar>
    </RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

如何使用LayoutInflater来获取ListView和ProgressBar并在代码中分配它?

BFi*_*Fil 25

通过这种方式:

View v = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
ListView listview = (ListView) v.findViewById(R.id.streamListView);
ProgressBar progress = (ProgressBar) v.findViewById(R.id.streamProgressBar);
Run Code Online (Sandbox Code Playgroud)


小智 7

您只需要活动参考并致电:

RelativeLayout relativeLayout = (RelativeLayout)activity.getLayoutInflater().inflate(R.layout.your_layout, null);
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它们的id获取两个视图

relativeLayout.findViewById(R.id.anId);
Run Code Online (Sandbox Code Playgroud)