如何在click方法的适配器类中从string.xml获取字符串

时间:2018-04-22 15:53:55

标签: java android android-recyclerview

我希望在点击方法中的视图持有者的适配器类中获取字符串我的应用程序崩溃时,我点击if(postion==1)实现下面的代码编写。

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{

    private Context context;
    String SongURL;
    private String[] data;
    public Adapter(String[] data){
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.activity_list_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        String title = data[position];
        holder.text.setText(title);
    }

    @Override
    public int getItemCount() {
        return data.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView img;
        TextView text;

        public ViewHolder(final View itemView) {
            super(itemView);
            img = (ImageView) itemView.findViewById(R.id.image1);
            text = (TextView) itemView.findViewById(R.id.text1);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int postion =getAdapterPosition();
                    if (postion==0){
                        String url = "http://sound41.songsbling.link/2016/english-songs/loud-rihanna/12%20-%20Love%20The%20Way%20You%20Lie%20Part%20I%20Bonus%20From%20Us%20%20-%20Loud%20-%20[SongsPK.city].mp3";
                        Intent intent = new Intent(v.getContext(),player.class);
                        intent.putExtra("url",url);
                        v.getContext().startActivity(intent);
                    }
                    if (postion==1){

                        // *This code crashes the app*
                        String url=Resources.getSystem().getString(R.string.song);

                    Intent intent = new Intent(v.getContext(),player.class);
                    intent.putExtra("url",url);
                    v.getContext().startActivity(intent);
                }
            }
        });

        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您查看docs,您会看到Resources.getSystem().getStrings将为您提供系统范围的字符串,而不是您应用程序中的字符串(strings.xml)。

替换以下行

String url = Resources.getSystem().getString(R.string.song);

以下内容。

String url = v.getContext().getResources().getString(R.string.song);

答案 1 :(得分:1)

您还可以在 Kotlin 的 apply 方法中使用 TextView 的上下文。

科特林:

textView.apply {
    context.resources.getString(R.string.your_string)
}