【发布时间】:2014-12-23 22:17:52
【问题描述】:
当应用程序用户在屏幕上按下时,我正在尝试通过在片段布局上绘制一个圆圈来做一些相对基本的事情。本质上是在用户按下的屏幕区域上画一个小圆圈。所以我从一个基本项目开始,在主布局中有一个片段。我有一个扩展 simpleOnGestureListener 的手势类。这会将我的圈子的坐标返回到主要活动。这很好用。但是在我调用 frag.drawCircle() 时,在主要活动的 onTouchEvent 方法中,我得到了一个 nullpointerexception,我不太清楚为什么会这样。下面是我的 MainActivity 的代码。我想我做的一切都是正确的,包括使用片段管理器获取片段并使用它的“标签”来检索片段?下面是我的主类的代码。
public class Circles extends Activity {
private GestureDetector detector;
private PlaceholderFragment frag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circles);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.activitylayout, new PlaceholderFragment(),"myfrag")
.commit();
}
detector = new GestureDetector(this, new Gestures());
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
boolean consumed = detector.onTouchEvent(event);
float x = Gestures.x;
float y = Gestures.y;
if(consumed)
{
Log.d("consumed? ", String.valueOf(consumed));
Log.d("x : ", String.valueOf(x));
Log.d("y : ", String.valueOf(y));
frag.drawCircle();
}
return super.onTouchEvent(event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.circles, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_circles, container, false);
return rootView;
}
public void drawCircle()
{
Log.d("stuff", "draw circle here!");
}
}
}
显然片段没有被正确实例化。我只是不太确定为什么会这样。非常感谢任何帮助。
【问题讨论】:
-
请发布您的 logcat 跟踪
-
如果您正在初始化片段,为什么不立即保存对它的引用呢?片段事务是异步执行的。如果要马上使用,需要拨打
getFragmentManager().executePendingTransactions(); -
好的。我认为使用片段管理器获取片段是检索片段的正确方法?
标签: android android-fragments android-studio