Reputation: 163
I am trying to call an activity from adapter class. My activity class has no constructor but onCreate()
. How do I call it from getView()
? I searched for solutions but it's not working.
My adapter getView()
:
public View getView(int position, View convertView, ViewGroup parent) {
//SharedPostView holder;
PostActivity holder;
if (convertView == null) {
Log.d("network frag list"," convertView null ");
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_post, null);
holder = new PostActivity();
convertView.setTag(holder);
} else {
Log.d("network frag list"," convertView.getTag() ");
holder = (PostActivity)convertView.getTag();
}
holder.init(position);
Log.d("network frag list", " getView");
return convertView;
}
Upvotes: 1
Views: 1095
Reputation: 5227
You need to understand the accessibility of the method startActivity()
. You can see the details of this method once you hit the ctrl+click
in the Android Studio
. Here is the detail , The class hierarchy up to Activity is as below-
Context (android.content)
ContextWrapper (android.content)
ContextThemeWrapper (android.view)
Activity (android.app)
the Context
class is having a abstract method.
public abstract void startActivity(Intent intent);
This is overridden in the class ContextWrapper
and the Activity
.
Hence you can call the method startActivity(Intent intent)
from any of the derived classes or from reference of the derived classes.
So you have are having reference of the Context
you can call the method as-
context.startActivity(intent)
Upvotes: 0
Reputation: 1924
Try this,
This is my getView from adapter class,
@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
View myView = convertView;
final ViewHolder holder;
try {
if (myView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
myView = inflater.inflate(R.layout.row_affiliates_list, null);
holder = new ViewHolder();
holder.txtAffiliateHeader = (TextView) myView.findViewById(R.id.txtAffiliateHeader);
holder.rlMain = (RelativeLayout) myView.findViewById(R.id.rlMain);
holder.viewLine = (TextView) myView.findViewById(R.id.viewLine);
myView.setTag(holder);
} else {
holder = (ViewHolder) myView.getTag();
}
holder.txtAffiliateHeader.setText(""+ AffiliatesList.get(position).getStrAffiliateTitle());
holder.rlMain.setTag(position);
holder.rlMain.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int arg2 = Integer.parseInt(v.getTag().toString());
Intent intent = new Intent(context, SecondActivity.class);
context.startActivity(intent);
}
});
return myView;
} catch (Exception e) {
return myView;
}
}
This is how you can call the activity from adapter class on click of your button or full relative layout.
Upvotes: 0