如何将当前的AttributeSet传递给自定义View类?如果我使用的参数中只有Context的构造函数,我将丢失所有主题,并在该自定义视图的xml中使用“style”标签的能力。
我所做的是创建一个包含我在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:
android:orientation="vertical"
android:id="@+id/mainlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
自定义视图类:
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:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_height="wrap_content"
android:text="Oh, Hewroh..."
style="?textview_style1" />