【发布时间】:2011-10-11 08:50:13
【问题描述】:
如果有任何帮助,我将不胜感激。
我创建了一个自定义组件 - MyButton 类,它扩展了 Button。我可以在构造函数中设置属性,但我不想这样做。我想在 xml 布局文件中设置属性。如何将属性放入构造函数中,以便在活动中创建新按钮时,使用 xml 布局文件创建新按钮?
我尝试过使用充气机,但它在类扩展按钮中不起作用。还有另一种方法吗? - 我花了几个小时在网上搜索,但没有任何令人满意的结果。
提前致谢
克莱夫
这是代码
public class CustomViewModify2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyButton myb = (MyButton)findViewById(R.id.mybutton1);
myb.setText("hello");
}
}
班级:
public class MyButton extends Button {
public MyButton(Context context) {
super(context);
this.setBackgroundColor(getResources().getColor(R.color.Red));
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.setBackgroundColor(getResources().getColor(R.color.Yellow));
}
}
main.xml`
<idig.za.net.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mybutton1"
/>
`
button_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/my_button_layout">
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="@color/Yellow" android:gravity="center"
android:width="100dp" android:textStyle="bold" android:textSize="24sp"
android:textColorLink="@color/Red"></Button>
【问题讨论】:
-
发布布局文件中的 xml
-
你看过这个教程吗? blog.pocketjourney.com/2008/05/02/…
-
嗨,是的,我有,但我觉得有点混乱。我尝试按照他们的示例操作我的代码,但没有成功。