Android从字符串包裹设置图像

时间:2018-10-25 04:43:38

标签: java android image arraylist parcelable

我正在尝试读取我的外部文本文件中的所有内容,并将其放入一个数组列表中,该列表通过宗地类发送给另一个类。虽然我可以在textview上设置字符串,但不能在图像上设置字符串。

外部文本文件中的其中一行如下所示:

McDonalds| Any McDonalds outlet| Applicable to any lunch meal set| Buy 1 get 1 free| 1 Aug - 31 Aug| RM 32.00| RM 16.00| icon_nandos.png

MainActivity.java:

public class MainActivity extends AppCompatActivity implements listAdapter.sendInfo{


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



    list_fragment lf = new list_fragment();

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.mainAct, lf);
    fragmentTransaction.commit();

}


@Override
public void detailInfo(outletData outDat, int pos) {
    fragmentDetail fd = fragmentDetail.newInstance(outDat);

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.mainAct, fd)
            .addToBackStack(null)
            .commit();
}
}

list_fragment.java:

public class list_fragment extends Fragment {
ArrayList<outletData> outletDatas = new ArrayList<outletData>();
BufferedReader bufferedReader = null;
String food;


public View onCreateView( LayoutInflater inflater,  @Nullable ViewGroup container,  Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.fragRecycler);
    outletDatas.clear();

    try{
        bufferedReader = new BufferedReader(new
                InputStreamReader(getContext().getAssets().open("food_catalog.txt")));
        while ((food = bufferedReader.readLine())!=null) {
            if (!food.equals("")) {
                String[] foodInfo = food.split("\\|");

                outletDatas.add(new outletData(foodInfo[0], foodInfo[1], foodInfo[2], foodInfo[3], foodInfo[4], foodInfo[5], foodInfo[6], foodInfo[7]));

            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    listAdapter mylistAdapter = new listAdapter(outletDatas, getContext());
    recyclerView.setAdapter(mylistAdapter);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);

    return view;
}

}

outletData.java:

package com.example.user.assignmentthreethree;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Parcel;
import android.os.Parcelable;

public class outletData implements Parcelable {
private String name, location, details, deals, offerPeriod, normalPrice, discountPrice, imagePath;

public outletData(String name, String location, String details, String deals, String offerPeriod, String normalPrice, String discountPrice, String imagePath) {
    this.name = name;
    this.location = location;
    this.details = details;
    this.deals = deals;
    this.offerPeriod = offerPeriod;
    this.normalPrice = normalPrice;
    this.discountPrice = discountPrice;
    this.imagePath = imagePath;
}

private outletData(Parcel in) {
    name = in.readString();
    location = in.readString();
    details = in.readString();
    deals = in.readString();
    offerPeriod = in.readString();
    normalPrice = in.readString();
    discountPrice = in.readString();
    imagePath = in.readString();
}

public static final Creator<outletData> CREATOR = new Creator<outletData>() {
    @Override
    public outletData createFromParcel(Parcel in) {
        return new outletData(in);
    }

    @Override
    public outletData[] newArray(int size) {
        return new outletData[size];
    }
};

public String getName() {
    return name;
}

public String getLocation() {
    return location;
}

public String getDetails() {
    return details;
}

public String getDeals() {
    return deals;
}

public String getOfferPeriod() {
    return offerPeriod;
}

public String getNormalPrice() {
    return normalPrice;
}


public String getDiscountPrice() {
    return discountPrice;
}


public String getImagePath() {
    return imagePath;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
    parcel.writeString(location);
    parcel.writeString(details);
    parcel.writeString(deals);
    parcel.writeString(offerPeriod);
    parcel.writeString(normalPrice);
    parcel.writeString(discountPrice);
    parcel.writeString(imagePath);

}
}

listAdapter.java:

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

ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;

listAdapter(ArrayList<outletData> outletDataFromFragment) {
    this.outletDataFromFragment = outletDataFromFragment;
}


@Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
 this.mContext = viewGroup.getContext();
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull listAdapter.ViewHolder viewHolder, int i) {
    outletData data = outletDataFromFragment.get(i);
    viewHolder.listName.setText(data.getName());
    viewHolder.listDeal.setText(data.getDeals());
    viewHolder.listOffer.setText(data.getOfferPeriod());
//        viewHolder.listImg.setImageURI(Uri.parse(data.getImagePath()));

    try {
        InputStream ims = mContext.getAssets().open(""+data.getImagePath().trim());
        Drawable d = Drawable.createFromStream(ims, null);
        viewHolder.listImg.setImageDrawable(d);
        ims.close();
    } catch (IOException ex) {
        return;
    }

}

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

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView listName, listDeal, listOffer;
    ImageView listImg;
    public ViewHolder(View itemView) {
        super(itemView);
        listName = (TextView)itemView.findViewById(R.id.txtName);
        listDeal = (TextView)itemView.findViewById(R.id.txtDeals);
        listOffer = (TextView)itemView.findViewById(R.id.txtOffer);
        listImg = (ImageView)itemView.findViewById(R.id.imgFood);
        recyclerView = (RecyclerView)itemView.findViewById(R.id.reCyclerView);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        ((sendInfo)view.getContext()).detailInfo(outletDataFromFragment.get(getLayoutPosition()), getLayoutPosition());
    }


}
interface sendInfo {
    void detailInfo(outletData outletData, int pos);
}
}

fragmentDetail.java:

public class fragmentDetail extends Fragment {
TextView  fragName, fragDeal, fragOffer, fragDetail, fragOldPrice, fragNewPrice, fragLocation;
ImageView fragImage;
outletData OD;

Bundle bundle;
public fragmentDetail() {}
public static fragmentDetail newInstance(outletData oData) {
    fragmentDetail fragmentDetail = new fragmentDetail();
    Bundle b = new Bundle();
    b.putParcelable("pData", oData);
    fragmentDetail.setArguments(b);
    return fragmentDetail;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bundle = this.getArguments();
    OD = bundle.getParcelable("pData");
}

@Override
public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_detail, container, false);
    fragName = (TextView)view.findViewById(R.id.frag_name);
    fragDeal = (TextView)view.findViewById(R.id.frag_Deal);
    fragOffer = (TextView)view.findViewById(R.id.frag_Offer);
    fragDetail = (TextView)view.findViewById(R.id.frag_Detail);
    fragOldPrice = (TextView)view.findViewById(R.id.frag_oldPrice);
    fragNewPrice = (TextView)view.findViewById(R.id.frag_newPrice);
    fragLocation = (TextView)view.findViewById(R.id.frag_location);

    fragImage = (ImageView)view.findViewById(R.id.frag_image);


    Toast.makeText(getContext(), OD.getImagePath(), Toast.LENGTH_LONG).show();

    fragOldPrice.setPaintFlags(fragOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    fragName.setText(OD.getName());
    fragDeal.setText(OD.getDeals());
    fragOffer.setText(OD.getOfferPeriod());
    fragDetail.setText(OD.getDetails());
    fragOldPrice.setText(OD.getNormalPrice());
    fragNewPrice.setText(OD.getDiscountPrice());
    fragLocation.setText(OD.getLocation());
    fragImage.setImageURI(Uri.parse(OD.getImagePath()));

    return view;
}
}

根据在线建议,我尝试修剪字符串,但不会改变结果。我仍在学习Android Studio的逻辑流程和语法,但是我不知道为什么即使图像与文本文件(Assests)在同一文件夹中,它也无法获取图像,却确实获取了food [7]字符串当我尝试将其打印时为icon_nandos.png。

1 个答案:

答案 0 :(得分:0)

您可以尝试从资产文件获取可绘制对象并将其设置为imageview。使用以下代码。

try {
    InputStream ims = getAssets().open(""+your_image_name);
    Drawable d = Drawable.createFromStream(ims, null);
    mImage.setImageDrawable(d);
    ims.close();
} catch(IOException ex) {
    return;
}

所以您需要按如下所示编辑代码。

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

ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;

listAdapter(ArrayList<outletData> outletDataFromFragment) {
    this.outletDataFromFragment = outletDataFromFragment;
}


@Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    this.mContext = viewGroup.getContext();
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull listAdapter.ViewHolder viewHolder, int i) {
    outletData data = outletDataFromFragment.get(i);
    viewHolder.listName.setText(data.getName());
    viewHolder.listDeal.setText(data.getDeals());
    viewHolder.listOffer.setText(data.getOfferPeriod());
    try {
        InputStream ims = mContext.getAssets().open(""+your_image_name);
        Drawable d = Drawable.createFromStream(ims, null);
        viewHolder.listImg.setImageDrawable(d);
        ims.close();
    } catch(IOException ex) {
        return;
    }
}