设置布局膨胀对象的重力,同时将其添加到视图中

时间:2015-12-01 12:05:17

标签: java android xml android-layout

我正在尝试通知inflater_layout.xml并将其添加到activity_main.xml。 任何人都可以让我知道如何在我将其添加到activity_main.xml时为inflater_layout.xml的视图对象分配重力?

inflater_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello I'm inflated"
android:textSize="40sp"
android:id="@+id/toBeInflated"
/>

activity_main.xml(包含列表视图)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
android:layout_width="match_parent"
android:layout_height="match_parent"    android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id = "@+id/relative"
android:paddingBottom="@dimen/activity_vertical_margin"         tools:context=".MainActivity">
<ListView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id = "@android:id/list">
</ListView>

MainActivity.java

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {
ListView l;
String[] days = {"Sunday", "Monday", "Tuesday", "Thursday", "Friday", "Saturday", "Sunday"};
LayoutInflater inflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    l = getListView();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_view_element, days);
    l.setAdapter(adapter);
    inflater = getLayoutInflater();
    l.setOnItemClickListener(this);
    RelativeLayout r = (RelativeLayout) findViewById(R.id.relative);
    View inf = inflater.inflate(R.layout.inflater_layout,r);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}
}

这是结果:

This is the outcome:

1 个答案:

答案 0 :(得分:3)

可以通过将LayoutParams添加到充气的View

来实现
//small change, attachToRoot = false:
View inf = inflater.inflate(R.layout.inflater_layout,r, false);
//LayoutParams always refer to the parent of the actual view:
RelativeLayout.LayoutParams lp  = new    RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//example Rule: 
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
inf.setLayoutParams(lp);
r.addView(inf) //because we haven't added it yet.

也许还要here查看attachToRoot = false的解释。