从RecyclerView适配器启动Chrome自定义选项卡

时间:2017-08-25 09:19:35

标签: java android android-recyclerview chrome-custom-tabs

我打算从const router = express.Router({ mergeParams: true }); router.get('/', ...); 这样启动一个Chrome Custom标签 -

RecyclerView

由于public CustomAdapter(Context context, List<Artifact> ListOfArtifacts) { this.context = context; this.ListOfArtifacts = ListOfArtifacts; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.artifactAuthor.setText(ListOfArtifacts.get(position).getAuthor()); holder.artifactTitle.setText(ListOfArtifacts.get(position).getTitle()); holder.seeders.setText(String.valueOf(ListOfArtifacts.get(position).getSeeders())); holder.leechers.setText(String.valueOf(ListOfArtifacts.get(position).getLeechers())); holder.addedOn.setText(df.format(ListOfArtifacts.get(position).getAdded_on())); holder.artifactTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { /*Intent launchArtifactAuthor = new Intent(Intent.parseUri(ListOfArtifacts.get(position).getURL(), Intent.URI_INTENT_SCHEME)); context.startActivity(launchArtifactAuthor);*/ CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder(); // Begin customizing // set toolbar colors intentBuilder.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary)); intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(context, R.color.colorPrimaryDark)); // set start and exit animations intentBuilder.setStartAnimations(context, android.R.anim.slide_out_right, android.R.anim.fade_in); intentBuilder.setExitAnimations(context, android.R.anim.slide_in_left, android.R.anim.slide_out_right); // build custom tabs intent CustomTabsIntent customTabsIntent = intentBuilder.build(); customTabsIntent.launchUrl((Activity) context, Uri.parse(ListOfArtifacts.get(position).getURL())); }catch (Exception e) { e.printStackTrace(); } } }); } 的方法签名要求第一个参数为customTabsIntent.launchUrl,我将上下文转换为Activity,因此

  

java.lang.ClassCastException:无法转换android.app.Application   到android.app.Activity

Activity

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果您在循环视图中总是需要活动,我认为获取Context并将其解析为Activity是没有意义的;而只是从构造函数中获取Activity。

因此我建议将构造函数更改为

public CustomAdapter(Activity activity, List<Artifact> ListOfArtifacts) {
    this.activity= activity;
    this.ListOfArtifacts = ListOfArtifacts;
}

只需使用活动即可启动Chrome custom tabs

customTabsIntent.launchUrl(activity, Uri.parse(ListOfArtifacts.get(position).getURL()));

如果您想知道您的代码有什么问题,我认为您正在传递应用程序上下文,而不是活动上下文。