如何在自定义适配器的列表中为其他项目创建自定义祝酒消息

时间:2018-11-15 14:59:55

标签: android

因此,我有一个程序,需要根据用户在列表中选择的项目来显示不同的吐司。我创建了一个自定义适配器,因为我需要将图片添加到列表中,并创建了一个名称为Day的对象,该名称包含星期几,图像和需要在烤面包中使用的自定义文本。我的问题是我不知道如何创建一个onItemClickListener来将我的自定义文本用于我的吐司。 这是我的自定义适配器

public class DayAdapter extends ArrayAdapter<Day> {

私有上下文mContext; int mResource;

public DayAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Day> objects) {
    super(context, resource, objects);
    mContext = context;
    mResource = resource;
}



@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    String jour = getItem(position).getDay();
    int image = getItem(position).getImage();
    String message = getItem(position).getMessage();

    Day journee = new Day(jour, image, message);

    LayoutInflater inflater = LayoutInflater.from(mContext);
    convertView = inflater.inflate(mResource, parent, false);

    TextView tvJour = (TextView) convertView.findViewById(R.id.textViewJour);
    ImageView tvImage = (ImageView) convertView.findViewById(R.id.imageViewJour);


    tvJour.setText(jour);
    tvImage.setImageResource(image);


    return convertView;
}

这是我的MainActivity

public class MainActivity extends AppCompatActivity {

ListView liste;

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

    liste = (ListView) findViewById(R.id.dayList);
    ArrayList<Day> semaine = new ArrayList<Day>();
    Day lundi = new Day("Lundi", R.drawable.happyface, "Prog lundi");
    Day mardi = new Day("Mardi", R.drawable.happyface, "Musique mardi");
    Day mercredi = new Day("Mercredi", R.drawable.happyface, "Mercredi");
    Day jeudi = new Day("Jeudi", R.drawable.beer, "Work jeudi");
    Day vendredi = new Day("Vendredi", R.drawable.beer, "also work vendredi");
    Day samedi = new Day("Samedi", R.drawable.malade, "also also work samedi");
    Day dimanche = new Day("Dimanche", R.drawable.etude, "Love Dimanche");

    semaine.add(lundi);
    semaine.add(mardi);
    semaine.add(mercredi);
    semaine.add(jeudi);
    semaine.add(vendredi);
    semaine.add(samedi);
    semaine.add(dimanche);

    DayAdapter adapter = new DayAdapter (this, R.layout.row, semaine);

    liste.setAdapter(adapter);

    liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String messa  = adapterView.getAdapter().getItem(i).toString();
            Toast.makeText(MainActivity.this, messa, Toast.LENGTH_LONG).show();
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

尝试在ArrayAdapter类中,特别是在getView方法(如

)中制作Toast
convertview.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View view) {
         Toast.makeText(mContext, "Custom Toast", Toast.LENGTH_SHORT).show();

     }

});

如果需要,可以使用onTouchListener代替onClickListener