start intent without onCreate {}

江枫思渺然 提交于 2020-07-24 03:24:16

问题


I have created a class which extends Gallery. There is no onCreate() method in super Class, and I'm unable to run my intent. This is my sample code:

 this.setOnItemClickListener(new AdapterView.OnItemClickListener() {

 @Override
 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
 Intent intent = new Intent(v.getContext(), ClassName.class);
 startActivity(intent);
}}

The following attempt also failed to work:

Intent intent = new Intent(ThisClassName.this, ClassName.class);
startActivity(intent);

Any advice would be greatly appreciated :)


回答1:


Actually, startActivity(); is the method of Activity class, To run this method you have to Context of Activity or Reference of Activity , You can not run this method in other class as outside of Activity scope without having Activity reference for it.

Try,

<Activity_Name>.this.startActivity(intent);

or

mContext.startActivity(intent);

Here mContext is reference of your Activity class.




回答2:


As you wrote, you want to start an Activity, if your class does not inherit from Activity (which I guess, because otherwise you WOULD HAVE TO implement onCreate()) you won't be able to start it with an Intent at all....




回答3:


If your class is the extends of the main activity and you want to call the other activity from the main body of the class, just simply create a method in the other class, then call the method by making an instance of the class and call the method.

Since they have the same nature, that will work, But remember to rap the method call in a try and catch method, otherwise you may get some errors.




回答4:


Gallery is a View type if you will see its Hirerchy you will see that its super class is View and view does't have any onCreate method

to use your CustomGallery

you can use it from xml or from code

<com.mypackage.CustomGallery >
android:id...


 </com.mypackage.CustomGallery>


来源:https://stackoverflow.com/questions/11222882/start-intent-without-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!