2017-08-25 94 views
0

我打算從RecyclerView這樣發動Chrome Custom標籤 -從RecyclerView適配器啓動Chrome的自定義標籤

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

就行customTabsIntent.launchUrl((Activity) context, Uri.parse(ListOfArtifacts.get(position).getURL()));

我該如何解決這個問題?

+0

目前尚不清楚你從哪裏獲得上下文。如果您從中獲得上下文,請添加構造函數。 – humazed

+0

@humazed - 添加了構造函數 – CodeWalker

+0

您還可以添加設置適配器的位置。 – humazed

回答

1

如果您在回收視圖中始終需要活動,我認爲獲取上下文並將其解析爲活動沒有意義;而只需從構造函數中獲取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())); 

的情況下,你想知道什麼是你的代碼錯誤,我想你是通過應用程序上下文,不活動上下文。

+0

工作正常!乾杯。 – CodeWalker