【问题标题】:Setting gravity of a layout inflated object while adding it to a view在将布局膨胀对象添加到视图时设置其重力
【发布时间】:2016-03-05 08:31:13
【问题描述】:

我正在尝试膨胀 inflater_layout.xml 并将其添加到 activity_main.xml。 谁能告诉我如何在将 inflater_layout.xml 的视图对象添加到 activity_main.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) {

}
}

这是结果:

【问题讨论】:

  • 在您的RelativeLayout 中将TextView 设置为不可见/消失(不占用空间)并使其在您想要的任何时候可见是否是一种解决方案?否则,您需要在 Java 代码中将一些 LayoutParams 添加到 TextView。
  • 您能详细说明一下添加 LayoutParams 吗?谢谢。

标签: java android xml android-layout


【解决方案1】:

可以通过将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 的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多