Подтвердить что ты не робот

Как передать AttributeSet в пользовательский вид

Как передать текущий 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>
4b9b3361

Ответ 1

Вместо того, чтобы строить его с помощью layout.addView(новый CustomLayout1 (getApplicationContext())); раздуйте его с помощью LayoutInflater в своей деятельности.

LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.yourcustomviewxml, layout);

Ответ 2

Ваш код создает LinearLayout внутри линейного макета для вашего пользовательского представления. Правильный способ сделать это - изменить свой пользовательский вид 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>

к

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="wrap_content"
      android:layout_height="wrap_content" 
      android:text="Oh, Hewroh..."
      style="?textview_style1" 
/>
</merge>

Ответ 3

Что вы пытаетесь сделать здесь? Похоже, у вас бесконечный рекурсивный цикл здесь, используя ваш метод create, так как inflate() вызовет конструктор, который принимает атрибуты. В любом случае, чтобы ответить на ваш вопрос, вы получаете атрибуты в конструкторе с атрибутами!

Это конструктор, который вызывается при загрузке из XML, иначе он вызывает один из других созданных вами конструкторов.

Еще одна полезная вещь, вы можете легко получить ссылку на надувной элемент из статического метода View. View.inflate: D