【发布时间】:2011-04-11 22:24:02
【问题描述】:
如何将当前的 AttributeSet 传递给自定义 View 类?如果我使用仅在参数中包含 Context 的构造函数,我将失去所有主题以及在该自定义视图的 xml 中使用“样式”标签的能力。
我所做的是在 xml 文件中创建一个包含我的自定义视图的活动,然后以编程方式创建一个新视图并将其添加到布局中。我发现在 xml 中制作的样式具有正确的样式,而我以编程方式创建的样式则没有。
据我所知,两者的区别在于系统使用CustomLayout1(Context context, AttributeSet attrs) 构造函数。问题是当我以编程方式创建它时,我无法弄清楚如何让应用程序的 AttributeSet 传递给这个自定义视图。
这是活动:
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class ThemeOne extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.mainlayout);
layout.addView(new CustomLayout1(getApplicationContext()));
}
}
这是主要的 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/mainlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.clearsync.test.theme1.CustomLayout1 android:id="@+id/maincustom"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
自定义视图类:
import com.clearsync.test.theme1.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
public class CustomLayout1 extends LinearLayout {
private Context context = null;
public CustomLayout1(Context context) {
super(context);
this.context = context;
create();
}
public CustomLayout1(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
create();
}
private void create(){
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.inflateme, this, true);
}
}
最后是自定义视图 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Oh, Hewroh..."
style="?textview_style1" />
</LinearLayout>
【问题讨论】:
标签: android