获取主要活动上下文

时间:2019-11-09 13:47:03

标签: java android fragment

我目前正在研究一个有7个类的Android项目:MainActivity,FragmentPagerAdapter,FragmentOne,FragmentTwo,RecyclerViewAdapter,Webview Fragment和Object类。

对象类(新闻)存储图像名称,标题,URL和日期。

FragmentOne和FragmentTwo是TabLayout的TabItem,它们是新闻的类别,由FragmentPagerAdapter处理。

CardView用于使用RecyclerViewAdapter填充两个片段。

但是问题是,在RecyclerViewAdapter中,我无法使用以下方法在cardview中显示图像:

getResources.getIdentifier(news.get(index).get_ImageName, drawable, mContext. getPackageName());

我猜是因为我从FragmentOne传递到RecyclerViewAdapter的上下文是片段上下文,而不是MainActivity的上下文?

以下是我的代码。

MainActivity:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ViewPager vp = findViewById(R.id.view_pager);
    MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
    vp.setAdapter(adapter);
}

FragmentPagerAdapter:

private String title[]={"Cybersecurity", "AI"};

public MyFragmentPagerAdapter(@NonNull FragmentManager fm) {
    super(fm);
}


@NonNull
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return new CybersecurityFragment();
        case 1:
            return new AIFragment();
    }
    return null;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return title[position];
}

@Override
public int getCount() {
    return title.length;
}

customAdapter:

private Context mContext;
private List<News> newsList;

public customAdapter(Context mContext, List<News> newsList) {
    this.mContext = mContext;
    this.newsList = newsList;
}

@NonNull
@Override
public MyViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view;
    LayoutInflater inflater = LayoutInflater.from(mContext);
    view = inflater.inflate(R.layout.card_view, parent, false);
    Log.d("Member", "pls1");
    return new MyViewholder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewholder holder, final int position) {
    holder.titleview.setText(newsList.get(position).getNews_title());
    int resID = mContext.getResources().getIdentifier(newsList.get(position).getImageName(), "drawable", mContext.getPackageName());
    Log.d("Member200", newsList.get(position).getImageName());
    Log.d("Member100", String.valueOf(resID));
    Log.d("Member", "pls");
    holder.imageview.setImageResource(resID);
    holder.cardview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Member", newsList.get(position).getNews_url());
            WebviewFragment fragment = WebviewFragment.newInstance(newsList.get(position).getNews_url());
            AppCompatActivity appCompatActivity = (AppCompatActivity) v.getContext();
            appCompatActivity.getSupportFragmentManager().beginTransaction().replace(R.id.cybersecurity_rv, fragment).addToBackStack(null).commit();
        }
    });
}


@Override
public int getItemCount() {
    return newsList.size();
}

public static class MyViewholder extends RecyclerView.ViewHolder{

    CardView cardview;
    TextView titleview;
    ImageView imageview;

    public MyViewholder(@NonNull View itemView) {
        super(itemView);
        cardview = itemView.findViewById(R.id.cardview);
        titleview = itemView.findViewById(R.id.textView_title);
        imageview = itemView.findViewById(R.id.imageView_image);

    }
}

FragmentOne:

private String category, news_title, image_name, news_urls;
private Date news_date;
private ArrayList<News> newsList = new ArrayList<>();
private ArrayList<News> cybersecurity_list = new ArrayList<>();


public CybersecurityFragment() {
    // Required empty public constructor
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_cybersecurity, container, false);
    try{
        final InputStream txtFile =getActivity().getAssets().open("news_items.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(txtFile));
        String line = reader.readLine();
        while (line!=null){
            int colonIndex = line.indexOf(":");
            if (line.contains("category")){
                category = line.substring(colonIndex+1);
            }
            else if (line.contains("photo")) {
                image_name = line.substring(colonIndex+1);
            }
            else if (line.contains("title"))
            {
                news_title = line.substring(colonIndex+1);
            }
            else if (line.contains("website"))
            {
                news_urls = line.substring(colonIndex+1);
            }
            else if (line.contains("date"))
            {
                DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
                news_date = format.parse(line.substring(colonIndex+1));
            }
            line = reader.readLine();
            if (category != null && image_name != null && news_title != null && news_urls != null && news_date != null){
                newsList.add(new News(category, image_name, news_title, news_urls, news_date));
                category = null;
                image_name = null;
                news_title = null;
                news_urls = null;
                news_date = null;
            }
        }
    } catch (Exception ie){
        ie.printStackTrace();
    }

    for (News n : newsList){
        if(n.getCategory().contains("cyber")) {
            cybersecurity_list.add(new News(n.getCategory(), n.getImageName(), n.getNews_title(), n.getNews_url(), n.getNews_date()));
            Log.d("Member", n.getImageName());
        } else {
            Log.d("Member", "no");
        }
    }

    RecyclerView rv_cs = view.findViewById(R.id.cybersecurity_rv);
    customAdapter adapter = new customAdapter(getContext(), cybersecurity_list);
    rv_cs.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL));
    rv_cs.setAdapter(adapter);
    return view;
}

请提供有关如何解决此问题的建议。谢谢大家!

1 个答案:

答案 0 :(得分:0)

编写一个Uitlity.java类

public static Drawable getDrawableFromName(Context context,String name){
    Resources resources = context.getResources();
    final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName());
    return resources.getDrawable(resourceId);
}
holder.imageview.setImageDrawable(Utility.getDrawableFromName(mContext,code));

这对我有用