我正在我的 Android 应用程序中实现一个功能,用户可以在其中动态添加和删除视图,FrameLayout
并通过使用拖放技术以绝对坐标定位它们。用户通常会加载平面图图像作为背景FrameLayout
,然后添加代表房屋中的灯的按钮并将它们放置在适当的位置。
无论如何,我有一个问题,我需要在加载FrameLayout
时膨胀并添加视图Fragment
。子视图源自 SQLite 数据库中的信息。为了正确定位子视图(取决于方向),我需要考虑FrameLayout
in 的宽度和高度。因此,我无法onCreateView()
在我的Fragment
.
FrameLayout
实际上是一个(为简单起见,DragArea
我仍将这个对象称为FrameLayout
),一个自定义类扩展FrameLayout
. 为了在Fragment
计算宽度/高度时获得回调,我重写onSizeChanged
了FrameLayout
调用Fragment
.
这是奇怪的事情。如果我在我的回调方法中Fragment
创建视图并调用FrameLayout.invalidate
似乎什么都没有发生。检查说视图已添加到视图中,FrameLayout
但没有看到。如果我打开hierarchyviewer 并按Load View Hierarchy 会出现视图。所以这里似乎有一个副作用,它会吸引人们的意见。我试图调用FrameLayout.requestLayout()
并通过执行逻辑来确保它在 UI 线程上运行,getActivity().runOnUiThread()
但这没有任何区别。
但!如果我将逻辑放在内部onPostExecuted()
(否则无用)AsyncTask
,则会绘制视图。
请参阅下面的代码,其中将在评论中进一步描述。回调方法被命名onWidthAvailable()
并从FrameLayout.onSizeChanged()
.
我还试图invalidate()
在以后的任意时间点打电话,但没有运气。
public class ImageFragment extends Fragment implements FragmentRedrawable, OnLongClickListener, OnWidthAvailableListener {
...
/*
* This will, among other things, inflate mPlanningView (A DragArea which extends FrameLayout). This is the FrameLayout that will contain the childs.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.fragment_image, null);
final ImageView image = (ImageView) view.findViewById(R.id.house_planning);
image.setImageResource(R.drawable.houseplanning);
mPlanningView = (com.doffman.dragarea.DragArea) view.findViewById(R.id.imageview);
image.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mPlanningView.invalidate();
setTouchPoint((int) event.getX(), (int) event.getY());
Log.d(Constants.TAG, String.format("Point (%f, %f)", event.getX(), event.getY()));
}
return false;
}
});
image.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
Log.d(Constants.TAG, "Show context menu for point: " + mTouchPoint.x + ", " + mTouchPoint.y);
MenuInflater inflater = new MenuInflater(getActivity());
inflater.inflate(R.menu.image_context_menu, menu);
}
});
mPlanningView.addDragListener(mPlanningView, new OnDragListener() {
@Override
public void onDrag(View view, final DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case com.doffman.dragarea.DragEvent.ACTION_DRAG_STARTED:
mActivity.disallowViewPagerInterception(true);
break;
case com.doffman.dragarea.DragEvent.ACTION_DROP:
final Bundle data = dragEvent.getBundle();
final String tag = data.getString("tagImageItem");
final Integer itemType = data.getInt("tagItemType");
final Integer itemId = data.getInt("tagItemId");
final View v = mPlanningView.findViewWithTag(tag);
if (v == null)
return;
animate(v).setDuration(0).x(dragEvent.getX()).y(dragEvent.getY());
mDb.setImageItemCoordinates(1, itemType, itemId, dragEvent.getX(), dragEvent.getY());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
moveView(v, dragEvent.getX(), dragEvent.getY());
}
});
break;
case com.doffman.dragarea.DragEvent.ACTION_DRAG_ENDED:
mActivity.disallowViewPagerInterception(false);
break;
default:
break;
}
}
});
mPlanningView.getLocationOnScreen(mPlanningViewCoordinates);
Log.d(Constants.TAG, "onCreateView: Width: " + mPlanningView.getWidth());
mPlanningView.setOnWidthAvailableListener(this);
return view;
}
/*
* This is called from mPlanningView.onSizeChanged() (i.e. when the width of
* mPlanningView has been calculated)
*
* This code will read information from SQLite and create Views that will be placed using
* coordinates defined in the database.
*/
@Override
public void onWidthAvailable() {
Log.d(Constants.TAG, "onWidthAvailable: Width is " + mPlanningView.getWidth());
if (mPlanningView.getWidth() == 0)
return;
mPlanningView.removeOnWidthAvailableListener();
/* The most natural thing would be to just do the logic directly. This will indeed add the
* views to mPlanningView but they are never drawn/seen.
Log.d(Constants.TAG, "onWidthAvailable thread: " + Thread.currentThread().getId());
List<ImageLayoutItem> items = mDb.getItemsForImagePage(1);
for (final ImageLayoutItem item : items) {
placeEntity(item);
}
*/
/* But if the logic is instead placed in an AsyncTask, the views are drawn */
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.d(Constants.TAG, "onPostExecute: UI thread: " + Thread.currentThread().getId());
List<ImageLayoutItem> items = mDb.getItemsForImagePage(1);
for (final ImageLayoutItem item : items) {
placeEntity(item);
}
}
}.execute();
}
private void moveView(View v, float xFactor, float yFactor) {
int xy[] = translateToAbsoluteCoordinates(xFactor, yFactor);
animate(v).setDuration(0).x(xy[0]).y(xy[1]);
FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) v.getLayoutParams();
p.leftMargin = xy[0];
p.topMargin = xy[1];
p.gravity = Gravity.TOP;
v.setLayoutParams(p);
mPlanningView.invalidate();
}
private int[] translateToAbsoluteCoordinates(float xFactor, float yFactor) {
int xy[] = new int[2];
float width = (float) mPlanningView.getWidth();
float relFloat = width * xFactor;
int relativeX = (int) (relFloat);
int relativeY = (int) ((float) mPlanningView.getHeight() * yFactor);
xy[0] = mPlanningViewCoordinates[0] + relativeX;
xy[1] = mPlanningViewCoordinates[1] + relativeY;
return xy;
}
public void placeEntity(ImageLayoutItem item) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
View itemLayout = inflater.inflate(item.getEntity().getItemLayoutId(prefs), null);
itemLayout.setTag(item.getEntity().getItemTypeId() + ":" + item.getEntity().getId());
itemLayout.setTag(R.id.tagItemType, item.getEntity().getItemTypeId());
itemLayout.setTag(R.id.tagItemId, item.getEntity().getId());
item.getEntity().setView(getActivity(), prefs, mProgressViewer, itemLayout, this);
if (!item.isShowTitle()) {
View entityName = itemLayout.findViewById(R.id.entityName);
if (entityName != null)
entityName.setVisibility(View.GONE);
}
if (item.isUseBackground()) {
itemLayout.setBackgroundColor(item.getBackgroundColor());
}
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
itemLayout.setLayoutParams(params);
mPlanningView.addView(itemLayout, params);
moveView(itemLayout, item.getXFactor(), item.getYFactor());
itemLayout.setOnLongClickListener(this);
}
...
}