Я реализовал и действие (называемое HomeScreenActivity), которое состоит из двух фрагментов.Один из них отображает список элементов, а другой отображает детали выбранного элемента.Фрагмент сведений (ResumeFragment в моем коде) состоит из ряда компонентов, которые пользователь может настроить по высоте и ширине, указав его в виде числа ячеек в файле конфигурации.Эти компоненты добавляются в пользовательский макет ComponentsLayout.
При открытии HomeScreenActivity я отображаю каждый фрагмент в методе onCreate, и они отображаются так, как задумано.Но когда я щелкаю и пункт во фрагменте списка элементов, и я заменяю resumeFragment новым экземпляром того же класса, ничего не отображается.
Я потратил много времени на отладку, и я вижу, что resumeFragment действительно заполняет заданную высоту и ширину, но у componentLayout есть только высота 1. Это я выяснил, потому чтовысота и ширина компонентов, содержащихся в компоненте Layout, не устанавливаются, хотя я установил их layoutParams в методе componentLayout onMeasure.
Ниже приведен код HomeScreenActivity, ResumeFragment и ComponentsLayout:
public class HomeScreenActivity extends FragmentActivity implements OnItemSelectedListener {
.
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
.
.
//Check if device is in landscape orientation
if(width > height && isTablet) {
//The patient context fragment must maintain the same width as when in portrait orientation.
findViewById(R.id.patient_resume_fragment_container).setLayoutParams(new LinearLayout.LayoutParams(height, height));
findViewById(R.id.screen_pager).setLayoutParams(new LinearLayout.LayoutParams(width-height, height));
fragmentManager = getSupportFragmentManager();
patientResumeFragment = new ResumeFragment();
testFragment = new NysomTestFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.patient_resume_fragment_container, patientResumeFragment);
fragmentTransaction.commit();
}
}
.
.
@Override
public void onItemSelected(Item item) {
itemResumeFragment.getView().findViewById(R.id.componentsContainer);
itemResumeFragment = new ResumeFragment(item);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.item_resume_fragment_container, itemResumeFragment);
fragmentTransaction.commit();
}
ResumeFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.resume_fragment,container, false);
ComponentsLayout componentsContainer = (ComponentsLayout) fragmentView.findViewById(R.id.componentsContainer);
placeComponents(componentsContainer);
return fragmentView;
}
private void placeComponents(ComponentsLayout layout) {
List<ComponentConfig> configs = new ArrayList<ComponentConfig>(testMobile.getModel().getComponentConfiguration());
int viewId = 1;
for (ComponentConfig currConfig : configs) {
ComponentsLayout.LayoutParams params = new ComponentsLayout.LayoutParams(0, 0);
params.setWidthInCells(currConfig.getWidth());
params.setHeightInCells(currConfig.getHeight());
if (viewId == 1) {
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
} else {
if (currConfig.getPositionX() > 0) {
// looking for rightOf viewId
params.addRule(RelativeLayout.RIGHT_OF, getRightOfComponentId(configs, currConfig, viewId - 1));
}
if (currConfig.getPositionY() > 0) {
// looking for below viewId
params.addRule(RelativeLayout.BELOW, getBelowComponentId(configs, currConfig, viewId - 1));
}
}
try {
// this code will be changed in story 9
View view = currConfig.getClassType().newInstance().getView(getActivity());
view.setId(viewId);
view.setBackgroundColor(colors[(viewId - 1) % 6]);
layout.addView(view, params);
} catch (Exception e) {
// we should never get to this point as configuration is validated
Log.e(TAG, "getView: unable to create component for position " + viewId, e);
throw new RuntimeException(e);
}
viewId++;
}
}
и ComponentLayout
public class ComponentsLayout extends RelativeLayout {
public ComponentsLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int horizontalCellsNum = getResources().getInteger(R.integer.resume_horizontal_cells_num);
int cellHeight = (int) (getResources().getDimension(R.dimen.resume_cell_height));
int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
LayoutParams params = (LayoutParams) child.getLayoutParams();
params.width = parentWidth * params.getWidthInCells() / horizontalCellsNum;
params.height = cellHeight * params.getHeightInCells();
child.setLayoutParams(params);
}
}
И снова, это работает при вызове из метода onScreate HomeScreenActivity, но не при выполнении из onItemSelectedМетод.
Может кто-нибудь помочь ??