Как передать текущий AttributeSet в пользовательский класс View? Если я использую конструктор, который имеет только контекст в аргументах, я теряю все темы и возможность использовать теги "style" в 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>