У меня возникли проблемы с созданием пользовательского представления.android: Пользовательский вид не отображается
Если мое понимание верное, я хочу создать сложный вид, в котором элементы ui, такие как Switch, могут быть включены в пользовательский вид. Примером такого намерения будет модальный вид, который отображает серию переключателей с кнопкой возврата & с относительными действиями в контексте цели приложения в приложении.
В других примерах/вопросах люди упомянули this.addView(View childView)
, однако, когда я пытаюсь использовать эту функцию, я получаю неразрешенную ошибку символа от студии android. При выполнении приложение отображает пустое.
public class NewView extends View {
private Switch switchOne;
private Switch switchTwo;
public NewView(Context context){
super(context);
init(null, 0);
}
public NewView(Context context, AttributeSet attrs){
super(context);
init(attrs, 0);
}
public NewView(Context context, AttributeSet attrs, int defStyle){
super(context);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
//LayoutInflater.from(getContext()).inflate(R.layout.customview, (ViewGroup) this.getParent(), true); //First attempted this approach
((Activity) getContext()).getLayoutInflater().inflate(R.layout.customview, (ViewGroup) this.getParent()); //then attempted this approach
this.switchOne = (Switch) findViewById(R.id.firstSwitch);
this.switchTwo = (Switch) findViewById(R.id.secondSwitch);
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
}
}
customview.xml
<?xml version="1.0" encoding="utf-8"?>
<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/mainView">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/firstSwitch"/>
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/secondSwitch"/>
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<com.example.simonaddicott.customviewone.NewView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/myNewView"
/>
</LinearLayout>
не Если ваш компонент расширения ViewGroup вместо View? – 2Dee
вместо получения контекста '(Activity) getContext()' лучше использовать переменную locar из конструктора. –
@ 2Dee - я не уверен, не так ли? ive исходят из фона какао iOS, поэтому предполагается, что пользовательский вид будет натурным расширением View. –