Как изменить цвет фона строки в представлении списка в соответствии со значением представления текста в представлении списка в Android Sudio? - PullRequest
0 голосов
/ 20 июня 2019

Я хочу создать список, который получает данные с сервера Ms Sql в Android Studio. Этот список включает в себя 5 различных данных в 1 строке. Я могу получить данные успешно, но я хочу показать список с 2 различными цветами в соответствии с 1 значением данных в каждой строке. Например, в этом ListView, если значение String TextView tv_CariNot равно "Gelir", тогда цвет фона этой строки показан ЗЕЛЕНЫМ, в противном случае цвет фона этой строки показан КРАСНЫМ. Мои коды классов Java такие:

public class CariInOut extends AppCompatActivity {

ListView lstCari;
Connection connect;
PreparedStatement stmt;
ResultSet rs;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cari_list);
        
    lstCari=(ListView) findViewById(R.id.lstCari);
        
    FillListCari fillList = new FillListCari();
    fillList.execute("");
        
 }
   public class FillListCari extends AsyncTask<String, String, String> {
        String z = "";

        List<Map<String, String>> carilist = new ArrayList<Map<String, String>>();

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(String r) {
            String[] from = {"A", "B", "C", "D", "E"};
            int[] views = {R.id.tv_CariTanim, R.id.tv_CariQty, R.id.tv_CariDate, R.id.tv_CariSube, R.id.tv_CariNot};
            final SimpleAdapter ADA = new SimpleAdapter(CariInOut.this,
                    carilist, R.layout.lsttempcari, from,
                    views);
            lstCari.setAdapter(ADA);


            lstCari.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    HashMap<String, Object> obj = (HashMap<String, Object>) ADA
                            .getItem(arg2);
                    String musteri = (String) obj.get("A");
                    String tutar = (String) obj.get("B");
                    String tarih = (String) obj.get("C");
                    String sube = (String) obj.get("D");
                    String cariTip = (String) obj.get("E");

                }
            });


        }

        @Override
        protected String doInBackground(String... params) {

            try {
                connect = CONN(DBun, DBpassword, DBName, DBip);
                if (connect == null) {
                    z = "SQL Server Connection Error";
                } else {
                    String queryAll = "exec sp_cari_listAll";

                    PreparedStatement ps = connect.prepareStatement(queryAll);
                    ResultSet rs = ps.executeQuery();

                    while (rs.next()) {
                        Map<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A", rs.getString("cari_not"));
                        datanum.put("B", rs.getString("tutar"));
                        datanum.put("C", rs.getString("tarih"));
                        datanum.put("D", rs.getString("sube_id"));
                        datanum.put("E", rs.getString("cari_tip"));


                        carilist.add(datanum);
                    }


                    z = "Success";
                }
            } catch (Exception ex) {
                z = "Error on getting data from table";

            }
            return z;
        }
    }
    }

, а также коды страниц lsttempcari.xml такие:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_CariTanim"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@color/design_default_color_primary_dark"
            android:textSize="18sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TUTAR"
            android:textStyle="italic" />

        <TextView
            android:id="@+id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TARİH"
            android:textStyle="italic" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="ŞUBE" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_CariQty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_CariDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/colorAccent"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_CariSube"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/colorAccent"
            android:textSize="10sp" />
    </LinearLayout>

    <TextView
        android:id="@+id/tv_CariNot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="@color/colorAccent"
        android:textStyle="bold" />

</LinearLayout>

В этом Listview (получение данных из MS SQL) tv_CariNot id TextView имеет только 2 различных строковых значения: «Gelir» и «Gider». Я хочу показать просмотр списка if (tv_CariNot.getText (). ToString () == "Gelir") row.backgroundcolor (Color.GREEN); if (tv_CariNot.getText (). toString () == "Gider") row.backgroundcolor (Color.RED);

Как мне этого добиться? Спасибо ..

Ответы [ 2 ]

0 голосов
/ 21 июня 2019

Я нашел такое решение: я изменил поле onPostExecute следующим образом:

protected void onPostExecute(String r) {

            pbbarCari.setVisibility(View.GONE);
            Toast.makeText(CariInOut.this, r, Toast.LENGTH_SHORT).show();

            String[] from = {"A", "B", "C", "D", "E"};
            int[] views = {R.id.tv_CariTanim, R.id.tv_CariQty, R.id.tv_CariDate, R.id.tv_CariSube, R.id.tv_CariNot};
            final SimpleAdapter ADA = new SimpleAdapter(CariInOut.this,
                    carilist, R.layout.lsttempcari, from,
                    views){
                public View getView(int position, View convertView, ViewGroup parent) {
                    View row = super.getView(position, convertView, parent);
                    
                    HashMap<String, Object> obj = (HashMap<String, Object>) getItem(position);

                    String cariTip = (String) obj.get("E");

                    if(cariTip.equals("Gelir"))
                    {
                        // do something change color
                        row.setBackgroundColor (Color.GREEN); // some color
                    }
                    else
                    {
                        // default state
                        row.setBackgroundColor (Color.RED); // default coloe
                    }
                    return row;
                }

            };
            lstCari.setAdapter(ADA);


            lstCari.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    HashMap<String, Object> obj = (HashMap<String, Object>) ADA
                            .getItem(arg2);
                    String musteri = (String) obj.get("A");
                    String tutar = (String) obj.get("B");
                    String tarih = (String) obj.get("C");
                    String sube = (String) obj.get("D");
                    String cariTip = (String) obj.get("E");

                }
            });


        }
0 голосов
/ 20 июня 2019

Я должен был добавить это как ответ, поскольку я не мог добавить комментарий. Обратитесь к этому ответу: https://stackoverflow.com/a/34707977/7844074

...