我正在开发一个基本上已经完成的应用程序,但我正在审查要优化的代码。我找到了一个充气指南,其中指出使用充气的“父”部分很好,这样你就可以保留布局参数——我在原始版本中没有这样做——而是我以编程方式设置这些。
现在继续解决问题。我已经更改了我的代码(如下所示)以合并视图,但没有添加布局参数,我仍然必须以编程方式添加它们。
原始代码,这可行,但是我对必须设置layoutparams不满意(请注意,我已经稍微缩短了代码以使其更易于阅读,我没有删除任何感兴趣的内容):
// this is the parent
LinearLayout llCategory = (LinearLayout) findViewById(R.id.llCategory);
categoryArrayList = db.getCategory(); // this gets the data for me.
// Add the Categories
for (int i = 0; i < categoryArrayList.size(); i++) {
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// This is my original inflate
//View view = layoutInflater.inflate(R.layout.row_standard, null);
// this is the inflate I would like to use.
View view = layoutInflater.inflate(R.layout.row_standard, llCategory, false);
LinearLayout llCard = (LinearLayout) view.findViewById(R.id.llStandardCard);
// here is some code where I change the background of llCard - which is the base layout for the view I inflated above.
// this is where I have to set the paddings programmatically on the view (or rather the linear layout that the view contains)
// get the right paddings for the card and set them.
int standardPadding = (int)getResources().getDimension(R.dimen.standard_padding);
int bottomPadding = (int)getResources().getDimension(R.dimen.standard_card_padding_bottom);
llCard.setPadding(standardPadding, standardPadding,standardPadding,bottomPadding);
// Add the complete view to the layout.
llCategory.addView(view);
}
所以回顾一下。不管我是否使用这个版本的 inflate: View view = layoutInflater.inflate(R.layout.row_standard, null);
或者如果我使用这个版本的膨胀: View view = layoutInflater.inflate(R.layout.row_standard, llCategory, false);
我必须以编程方式设置填充(已在 XML 中设置) - 我做错了什么。
编辑,添加 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/llStandardCard"
style="@style/StandardCardStyle">
<TextView
android:id="@+id/tvStandardRowText"
style="@style/RowText"/>
</LinearLayout>
</LinearLayout>
还有风格:
<style name="StandardCardStyle" parent="@style/AbstractCard">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginTop">@dimen/standard_half_padding</item>
<!--Very custom paddings due to the background messing with the standard ones-->
<item name="android:paddingLeft">@dimen/standard_padding</item>
<item name="android:paddingRight">@dimen/standard_padding</item>
<item name="android:paddingTop">@dimen/standard_padding</item>
<item name="android:paddingBottom">@dimen/standard_card_padding_bottom</item>
<item name="android:layout_gravity">top</item>
<item name="android:clickable">true</item>
</style>