当前位置: 首页 > 面试题库 >

我无法在TextView中显示计时器

佘修为
2023-03-14
问题内容

我用倒数计时器创建了一个Listview,下面是代码:

public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{

    private ArrayList<TicketModel> dataSet;
    Context mContext;
    long timeLeftMS ;

    // View lookup cache
    private class ViewHolder {
        TextView txtName;
        TextView txtType;
        TextView txtTempsRestant;
        TextView txtDate;
        TextView txtSLA;
        ImageView info;
        RelativeLayout layout;

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                System.out.println("handler");

                int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
                int minute = (int) ((timeLeftMS / (60000)) % 60);
                int seconde = (int)timeLeftMS % 60000 / 1000;

                String timeLeftText = "";

                if (hour<10) timeLeftText += "0";
                timeLeftText += hour;
                timeLeftText += ":";
                if (minute<10) timeLeftText += "0";
                timeLeftText += minute;
                timeLeftText += ":";
                if (seconde<10) timeLeftText += "0";
                timeLeftText += seconde;

                txtTempsRestant.setText(timeLeftText);
            }
        };

    }


    public TicketAdapter(ArrayList<TicketModel> data, Context context) {
        super(context, R.layout.row_item_ticket, data);
        this.dataSet = data;
        this.mContext=context;
        //startUpdateTimer();
    }


    @Override
    public void onClick(View v) {
        int position=(Integer) v.getTag();
        Object object= getItem(position);
        TicketModel TicketModel=(TicketModel)object;

        switch (v.getId())
        {
            case R.id.item_info:

                Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }
    }

    private int lastPosition = -1;


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        TicketModel TicketModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        final ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
            viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
            viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
            viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
            viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
            viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);


            result=convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);
        lastPosition = position;

        viewHolder.txtName.setText(TicketModel.getTitreTicket());
        viewHolder.txtDate.setText(TicketModel.getDateTicket());
        viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
        //viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
        viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
        viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
        viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);

        System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
        System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct

        timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());


        startTimer(viewHolder.handler);



        // Return the completed view to render on screen
        return convertView;
    }

    private void startTimer(final Handler handler) {
        CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {

            @Override
            public void onTick(long l) {
                timeLeftMS = l;
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFinish() {

            }
        }.start();
    }


    private int getColorBG(boolean ticketEnRetard) {
        int color;

        if (ticketEnRetard){
            color = Color.parseColor("#3caa0000");
        }
        else{
            color = Color.parseColor("#ffffff");
        }
        return color;
    }



    private int getIconUrgence(String urgenceTicket) {
        int icon;

        if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
            icon = R.drawable.basse;
        }
        else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
            icon = R.drawable.haute;
        }
        else {
            icon = R.drawable.moyenne;
        }

        return icon;
    }


}

TicketModel 类:

public class TicketModel {
    String titreTicket;
    String slaTicket;
    String DateTicket;

    String UrgenceTicket;

    boolean ticketEnRetard;

    String TempsRestantTicket;

    public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
        this.titreTicket = titreTicket;
        this.slaTicket = slaTicket;
        DateTicket = dateTicket;
        TempsRestantTicket = tempsRestantTicket;
    }

    public String getTitreTicket() {
        return titreTicket;
    }

    public String getSlaTicket() {
        return slaTicket;
    }

    public String getDateTicket() {
        return DateTicket;
    }

    public String getUrgenceTicket() {
        return UrgenceTicket;
    }

    public void setUrgenceTicket(String urgenceTicket) {
        UrgenceTicket = urgenceTicket;
    }

    public void setTempsRestantTicket(String tempsRestantTicket) {
        TempsRestantTicket = tempsRestantTicket;
    }

    public String getTempsRestantTicket() {
        return TempsRestantTicket;
    }

    public boolean isTicketEnRetard() {
        return ticketEnRetard;
    }

    public void setTicketEnRetard(boolean ticketEnRetard) {
        this.ticketEnRetard = ticketEnRetard;
    }
}

我在哪里填充ListView:

public class ListTickets extends AppCompatActivity {

    ArrayList<TicketModel> TicketModels;
    ListView listView;
    private static TicketAdapter adapter;
    String session_token, nameUser, idUser, firstnameUser, nbTicket;
    RequestQueue queue;
    String titreTicket, slaTicket, urgenceTicket,
    demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
            dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
    boolean ticketEnretard;

    public static int nbTicketTab = 6;
    public static int nbInfoTicket = 12;

    public static String[][] ticketTab ;
    public static String[][] infoTicket ;

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

        queue = Volley.newRequestQueue(this);

        Intent i = getIntent();
        session_token = i.getStringExtra("session");
        nbTicket = i.getStringExtra("nb");
        nameUser = i.getStringExtra("nom");
        firstnameUser = i.getStringExtra("prenom");
        idUser = i.getStringExtra("id");

        listView=(ListView)findViewById(R.id.list);


        TicketModels = new ArrayList<>();
        ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
        infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];


        String url = FirstEverActivity.GLPI_URL+"search/Ticket";



        List<KeyValuePair> params = new ArrayList<>();
        params.add(new KeyValuePair("criteria[0][field]","5"));
        params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
        params.add(new KeyValuePair("criteria[0][value]",idUser));
        params.add(new KeyValuePair("forcedisplay[0]","4"));
        params.add(new KeyValuePair("forcedisplay[1]","10"));
        params.add(new KeyValuePair("forcedisplay[2]","7"));
        params.add(new KeyValuePair("forcedisplay[3]","12"));
        params.add(new KeyValuePair("forcedisplay[4]","15"));
        params.add(new KeyValuePair("forcedisplay[5]","30"));
        params.add(new KeyValuePair("forcedisplay[6]","18"));
        params.add(new KeyValuePair("forcedisplay[7]","21"));
        params.add(new KeyValuePair("forcedisplay[8]","83"));
        params.add(new KeyValuePair("forcedisplay[9]","82"));
        params.add(new KeyValuePair("forcedisplay[10]","16"));

        final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray Jdata = response.getJSONArray("data");
                            for (int i=0; i < Jdata.length(); i++) {
                                    try {
                                        JSONObject oneTicket = Jdata.getJSONObject(i);
                                        // Récupération des items pour le row_item
                                        titreTicket = oneTicket.getString("1");
                                        slaTicket = oneTicket.getString("30");
                                        dateDebutTicket = oneTicket.getString("15");
                                        urgenceTicket = oneTicket.getString("10");

                                        //Récupération du reste
                                        demandeurTicket = oneTicket.getString("4");
                                        categorieTicket = oneTicket.getString("7");
                                        etatTicket = oneTicket.getString("12");
                                        dateEchanceTicket = oneTicket.getString("18");
                                        descriptionTicket = oneTicket.getString("21");

                                        lieuTicket = oneTicket.getString("83");
                                        dateClotureTicket = oneTicket.getString("16");
                                        ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));


                                        System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
                                    } catch (JSONException e) {
                                        Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
                                    }


                                ticketTab[i][0] = titreTicket;
                                ticketTab[i][1] = slaTicket;
                                ticketTab[i][2] = dateDebutTicket;
                                ticketTab[i][3] = urgenceText(urgenceTicket);
                                ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
                                ticketTab[i][5] = String.valueOf(ticketEnretard);




                                infoTicket[i][0] = demandeurTicket;
                                infoTicket[i][1] = urgenceText(urgenceTicket);
                                infoTicket[i][2] = categorieTicket;
                                infoTicket[i][3] = etatText(etatTicket);
                                infoTicket[i][4] = dateDebutTicket;
                                infoTicket[i][5] = slaTicket;
                                infoTicket[i][6] = dateEchanceTicket;
                                infoTicket[i][7] = titreTicket;
                                infoTicket[i][8] = descriptionTicket;
                                infoTicket[i][9] = lieuTicket;
                                infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
                                infoTicket[i][11] = dateClotureTicket;

                                System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
                                System.out.println("SLA = "+slaTicket);
                                System.out.println("Between : "+getBetweenBrackets(slaTicket));
                                System.out.println("Minimum : "+getMinTemps(slaTicket));
                                System.out.println("Maximim : "+getMaxTemps(slaTicket));



                            }


                            System.out.println("*** Tab Ticket ***");
                            System.out.println("isLate: "+ticketTab[0][5]);
                            System.out.println("\n\n*** Info Ticket ***");
                            System.out.println("Titre: "+infoTicket[0][7]);

                            // Populate the ListView
                            addModelsFromTab(ticketTab);

                            adapter = new TicketAdapter(TicketModels,getApplicationContext());

                            listView.setAdapter(adapter);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                    TicketModel TicketModel= TicketModels.get(position);

                                    Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
                                            .setAction("No action", null).show();

                                    Intent i = new Intent(getApplicationContext(), InfoTicket.class);
                                    i.putExtra("session",session_token);
                                    i.putExtra("nom",nameUser);
                                    i.putExtra("prenom",firstnameUser);
                                    i.putExtra("id",idUser);
                                    i.putExtra("infoTicket", infoTicket[position]);

                                    startActivity(i);



                                }
                            });


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //progressBar.setVisibility(View.GONE);
                        Log.e("Error.Response", error.toString());
                    }

                }
        ){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("App-Token",FirstEverActivity.App_Token);
                params.put("Session-Token",session_token);
                return params;
            }

        };

        // add it to the RequestQueue
        queue.add(getRequest);

    }


        private void addModelsFromTab(String[][] ticketTab) {
        for (int i = 0; i < ticketTab.length; i++){
                TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
                ticket.setUrgenceTicket(ticketTab[i][3]);
                ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
                //ticket.setTempsRestantTicket(ticketTab[i][4]);

                TicketModels.add(ticket);
        }
    }


    private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
        String minTemps = getMinTemps(slaTicket);
        String maxTemps = getMaxTemps(slaTicket);

        long dateDebutMS = getDateDebutMS(dateDebutTicket);
        long currentTimeMS = CurrentTimeMS();

        long minTempsMS = hourToMSConvert(minTemps);

        long differenceCurrentDebut = currentTimeMS - dateDebutMS;

        long tempsRestant = minTempsMS - differenceCurrentDebut;

        return String.valueOf(tempsRestant);
    }


}

我的问题是我想timeLeftTexttxtTempsRestantTextView中显示计时器(字符串),但无法访问它。谁能给我建议?

当我在控制台中打印并且输出正确时,但无法显示它。我应该改变工作方式吗?


问题答案:

修改了Adapter类以使倒计时工作正常。

public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{

    private ArrayList<TicketModel> dataSet;
    Context mContext;

    // View lookup cache
    private class ViewHolder {
        TextView txtName;
        TextView txtType;
        TextView txtTempsRestant;
        TextView txtDate;
        TextView txtSLA;
        ImageView info;
        RelativeLayout layout;

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                System.out.println("handler");

                Bundle bundle = msg.getData();
                long timeLeftMS = bundle.getLong("time");
                int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
                int minute = (int) ((timeLeftMS / (60000)) % 60);
                int seconde = (int)timeLeftMS % 60000 / 1000;

                String timeLeftText = "";

                if (hour<10) timeLeftText += "0";
                timeLeftText += hour;
                timeLeftText += ":";
                if (minute<10) timeLeftText += "0";
                timeLeftText += minute;
                timeLeftText += ":";
                if (seconde<10) timeLeftText += "0";
                timeLeftText += seconde;

                txtTempsRestant.setText(timeLeftText);
            }
        };

        public void startTimer(long timeLeftMS) {
            CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {

                @Override
                public void onTick(long l) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("time", l);
                    Message message = new Message();
                    message.setData(bundle);
                    handler.sendMessage(message);
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }

      }


    public TicketAdapter(ArrayList<TicketModel> data, Context context) {
        super(context, R.layout.row_item_ticket, data);
        this.dataSet = data;
        this.mContext=context;
        //startUpdateTimer();
    }


    @Override
    public void onClick(View v) {
        int position=(Integer) v.getTag();
        Object object= getItem(position);
        TicketModel TicketModel=(TicketModel)object;

        switch (v.getId())
        {
            case R.id.item_info:

                Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }
    }

    private int lastPosition = -1;


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        TicketModel TicketModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        final ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
            viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
            viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
            viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
            viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
            viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);


            result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);
        lastPosition = position;

        viewHolder.txtName.setText(TicketModel.getTitreTicket());
        viewHolder.txtDate.setText(TicketModel.getDateTicket());
        viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
        //viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
        viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
        viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
        viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);

        System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
        System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct

        // Return the completed view to render on screen
        return convertView;
    }

    private int getColorBG(boolean ticketEnRetard) {
        int color;

        if (ticketEnRetard){
            color = Color.parseColor("#3caa0000");
        }
        else{
            color = Color.parseColor("#ffffff");
        }
        return color;
    }



    private int getIconUrgence(String urgenceTicket) {
        int icon;

        if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
            icon = R.drawable.basse;
        }
        else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
            icon = R.drawable.haute;
        }
        else {
            icon = R.drawable.moyenne;
        }

        return icon;
    }


}


 类似资料:
  • 我正在尝试为一个活动构建一个票务预订应用程序,我设法完成了注册和登录部分。登录后,用户配置文件会显示出来,其中包含一些关于姓名、年龄、电子邮件等的文本视图。我想从实时数据库中读取数据并将其放入文本视图中。我不知道问题出在哪里,但文本视图不会显示数据。 用户配置文件类 用户类

  • 问题内容: 我有简单的 HTML : 我想在中显示HTML样式的文本。这个怎么做? 问题答案: 您需要使用XML字符串中的HTML。仅在布局XML中引用带有HTML的字符串将不起作用。 这是您应该做的:

  • 我知道以前有人问过这个问题,但那篇文章中的解决方案对我不起作用。 我刚刚开始学习Android编程,当时正在做一个模型。它可以在Android Studio中正确显示,但不能在我的设备上显示。图像和背景色显示正确,但没有文本显示。我试过改变字体和字体颜色。需要改变什么? 我有另一个使用RelativeLayout的示例,它显示正确,但这个ConstraintLayout不正确。 第一个图像来自AS

  • 问题内容: 我有一些HTML数据,其中包含标题,段落,图像和列表标签。 是否有一个显示该数据的方式还是? 问题答案: 对于Swift 4: 然后,每当您要将HTML文本放入UITextView时,请使用:

  • 我刚刚开始尝试Android应用程序开发,所以我决定尝试一下Android自己的教程(这个:http://developer.android.com/training/basics/firstapp/starting-activity.html) 我的新活动中的文本视图不会显示。这是我的代码:

  • 我有代码在这里生成一个随机的名字给定音节点击一个动作按钮。但作为字符串currentName生成的名称会显示在TextView中。我需要使视图成为它自己的类吗?我是androidstudio的新手,来自eclipse,所以textviews对我来说也是新手。多谢了。 } 这也是我的activity_main.xml