【问题标题】:finding Context name inside an Adapter在适配器中查找上下文名称
【发布时间】:2020-05-05 20:19:54
【问题描述】:

我无法理解是哪个活动启动了我的适配器。 这两个活动对适配器的请求几乎相同,所以我认为在 2 个活动中为两个 recyclerViews 使用相同的适配器。 出于某种原因,在调试器中我发现(显然) context.getApplicationInfo().name 具有价值,但是当我尝试使用“g”时它等于 null...

public class CustomCatalogAdapter extends RecyclerView.Adapter<CustomCatalogAdapter.MyViewHolder>{

   private Context mContext;
   ...

   @Override
   public void onBindViewHolder(CustomCatalogAdapter.MyViewHolder holder, final int position) {
       ApplicationInfo applicationInfo = mContext.getApplicationInfo();
       String g = applicationInfo.name;
   }
}

【问题讨论】:

    标签: android-studio android-recyclerview android-context


    【解决方案1】:

    搜索了Context的getApplicationInfo()、getApplicationContext()等函数后找到了答案。看了亚历山大卢卡斯的回答后:

    https://stackoverflow.com/a/10641257/11388670

    我理解 getContext() "返回视图当前正在运行的上下文。通常是当前活动的 Activity。"

    所以,我备份并尝试了 mContext 上的功能,直到我发现我的适配器在哪里运行:

    String myActivityName = mContext.getClass().getSimpleName();

    上面写的将为您提供您的活动名称,就像您在创建它时最初命名的一样。 对于包名称,请改用:

    mContext.getClass().getName()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多