在Android中以编程方式设置自定义属性
我有以下自定义属性:在Android中以编程方式设置自定义属性,android,android-layout,android-custom-view,Android,Android Layout,Android Custom View,我有以下自定义属性: <declare-styleable name="BoxGridLayout"> <attr name="numColumns" format="integer" /> <attr name="numRows" format="integer" /> <attr name="separatorWidth" format="dimension" /> <att
<declare-styleable name="BoxGridLayout">
<attr name="numColumns" format="integer" />
<attr name="numRows" format="integer" />
<attr name="separatorWidth" format="dimension" />
<attr name="separatorColor" format="color" />
<attr name="equalSpacing" format="boolean" />
</declare-styleable>
我们需要在xml视图布局中设置它们:
<com.github.ali.android.client.customview.view.PadLayout
android:id="@+id/padLayout"
style="@style/PadLayoutStyle"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
custom:numColumns="3"
custom:numRows="4"
custom:separatorColor="@color/dialer_theme_color"
custom:separatorWidth="1dp">
如何在java代码中以编程方式而不是通过xml中的自定义命名空间设置这些自定义属性?您可以使用LayoutParams。例如:
LinearLayout parent=new LinearLayout(this);
View child=new View(this);
float density =getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams lllp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lllp.setMargins((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
lllp.gravity=Gravity.CENTER;
child.setPadding((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
child.setLayoutParams(lllp);
parent.addView(child);
将setter添加到
PadLayout
不是一个选项吗?这是人们通常做的事。?你的PadLayout是一个customView,所以你需要在你的类中有这些属性。所有这些看起来都像一个类成员变量。您是否尝试过使用setter方法动态设置值,然后重新绘制视图?
LinearLayout parent=new LinearLayout(this);
View child=new View(this);
float density =getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams lllp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lllp.setMargins((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
lllp.gravity=Gravity.CENTER;
child.setPadding((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
child.setLayoutParams(lllp);
parent.addView(child);