Я пытался раздуть представления из xml до соответствующих им объектов представления, а затем добавить эти объекты представления в запрограммированную группу просмотра. Однако всякий раз, когда я вызываю myviewgroup.addView(childview), дочернее представление, кажется, теряет все кнопки и вещи, которые должен был дать ему код xml. Однако единственное, что есть у дочернего представления, — это цвет фона, который я запрограммировал, чтобы гарантировать, что дочернему представлению были заданы правильные размеры. Дочернему представлению присваиваются правильные размеры, но ни один из его компонентов не виден
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
viewchanger= new ViewChanger(this); //my viewgroup
View mainmenu= inflater.inflate(R.layout.main, null); //the xml code
mainmenu.setBackgroundColor(Color.rgb(0, 0, 255));
viewchanger.addView(mainmenu);
setContentView(viewchanger);
приведенный выше код просто устанавливает синий фон моего экрана, но ни одна из кнопок не отображается. Кроме того, когда я устанавливаюContentView(mainmenu), все отлично отображается из этого XML-кода, а также цвет фона. Смысл этой группы просмотра в том, что я могу переключаться между любым из нескольких представлений независимо от их порядка в качестве дочерних.
Вот код видчейнджера. Я хочу, чтобы у него было 7 дочерних представлений, и когда я вызываю метод setView(int v), я хочу, чтобы все остальные представления исчезли, и я хочу, чтобы отображалось только одно представление.
public class ViewChanger extends ViewGroup{
/**Represent which view to show, only one can show at a time*/
public static final int MainMenu=0, ChooseMap=1, MapOptions=2,
SetLocation=3, view=4, EditMap=5, CreateMap=6;
private int current; //the current view
private View[] views= new View[7];
public ViewChanger(Context context) {
super(context);
//load 7 views into view array here
//LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
/*views[0]= inflater.inflate(R.layout.main, null);
* views[1]= inflater.inflate(R.layout.choose, null);
* views[2]= inflater.inflate(R.layout.mapoptions, null);
* views[0].setBackgroundColor(Color.rgb(255, 0, 0));
* views[1].setBackgroundColor(Color.rgb(255, 255, 0));
* views[2].setBackgroundColor(Color.rgb(0, 255, 0));*/
* addView(views[0]);
* addView(views[1]);
* addView(views[2]);
* this is how i want to load the childviews*/
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for(int i = 0; i < getChildCount(); i++){
getChildAt(i).layout(0, 0, getWidth(), getHeight());
}
}
/**Sets the view of the view group, only one view can be viewed at a time*/
public void setView(int v){
current=v;
for (int i=0; i<views.length; i++){
if (v==i){
views[i].setVisibility(View.VISIBLE);
} else{
views[i].setVisibility(View.GONE);
}
}
}
Когда я загружаю дочерние представления в конструкторе ViewChanger, группа просмотра показывает мне только цвета фона того представления, которое я установил с помощью setView(int v), а не кнопки.
Вот код xml для main, но все остальные выглядят очень похоже на это:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="The title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome [...]"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/load"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Load Map" />
<Button
android:id="@+id/create"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Create Map" />
<Button
android:id="@+id/users"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:text="Other User" />
</LinearLayout>