繁体   English   中英

如何以编程方式更改列表项的背景?

[英]How do I change list item's background programatically?

我目前正在尝试做的是将ListView每一行更改为特定的背景。

我正在从SQLite加载所有信息。 我可以将图片加载到文本旁边,但是不能将要使用的图像放到特定的行中作为背景。

ForthActivity.java

public class ForthActivty extends AppCompatActivity implements
     View.OnClickListener   {

     private EditText  pastetext;
     private ClipboardManager myClipboard;


     private ProgressDialog loading;
     protected ListView lv;
     protected ListAdapter adapter;
     SQLiteDatabase db;
     Cursor cursor;
     EditText et_db;

     @SuppressWarnings("deprecation")
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_forth_activty);
         myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
         pastetext = (EditText) findViewById(R.id.textView1);


         db = (new DB_Resep(this)).getWritableDatabase();
         lv = (ListView) findViewById(R.id.lv);
         et_db = (EditText) findViewById(R.id.et);

         try {
             cursor = db.rawQuery("SELECT * FROM resep ORDER BY nama ASC", null);
             adapter = new SimpleCursorAdapter(this, R.layout.isi_lv, cursor,
                     new String[] { "nama", "bahan", "img" }, new int[] {
                     R.id.tv_nama, R.id.tvBahan, R.id.imV });
             lv.setAdapter(adapter);
             lv.setTextFilterEnabled(true);
             lv.setOnItemClickListener(new OnItemClickListener() {

                 @Override
                 public void onItemClick(AdapterView<?> parent, View v,
                                         int position, long id) {
                     detail(position);

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

     }

     @SuppressWarnings("deprecation")
     public void search_db(View v) {
         String edit_db = et_db.getText().toString();
         if (!edit_db.equals("")) {
             try {
                 cursor = db.rawQuery("SELECT * FROM resep WHERE nama LIKE ?",
                         new String[] { "%" + edit_db + "%" });
                 adapter = new SimpleCursorAdapter(
                         this,
                         R.layout.isi_lv,
                         cursor,
                         new String[] { "nama", "bahan", "img" },
                         new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
                 if (adapter.getCount() == 0) {
                     Toast.makeText(
                             this,
                             "Nu am putut gasi reteta dumneavoastra " + edit_db
                                     + "", Toast.LENGTH_SHORT).show();
                 } else {
                     lv.setAdapter(adapter);
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }
         } else {
             try {
                 cursor = db.rawQuery("SELECT * FROM resep ORDER BY nama ASC",
                         null);
                 adapter = new SimpleCursorAdapter(
                         this,
                         R.layout.isi_lv,
                         cursor,
                         new String[] { "nama", "bahan", "img" },
                         new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
                 lv.setAdapter(adapter);
                 lv.setTextFilterEnabled(true);
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }

     @SuppressLint("NewApi")
     public void paste(View view) {
         ClipData cp = myClipboard.getPrimaryClip();
         ClipData.Item item = cp.getItemAt(0);
         String text = item.getText().toString();
         pastetext.setText(text);
         Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);}

     public void detail(int position) {
         int im = 0;
         String _id = "";
         String nama = "";
         String bahan = "";
         String cara = "";
         if (cursor.moveToFirst()) {
             cursor.moveToPosition(position);
             im = cursor.getInt(cursor.getColumnIndex("img"));
             nama = cursor.getString(cursor.getColumnIndex("nama"));
             bahan = cursor.getString(cursor.getColumnIndex("bahan"));
             cara = cursor.getString(cursor.getColumnIndex("cara"));
         }

         Intent iIntent = new Intent(this, DB_Parse.class);
         iIntent.putExtra("dataIM", im);
         lv.setBackground(R.drawable.+ "im");
         iIntent.putExtra("dataNama", nama);
         iIntent.putExtra("dataBahan", bahan);
         iIntent.putExtra("dataCara", cara);
         setResult(RESULT_OK, iIntent);
         startActivityForResult(iIntent, 99);
     int res = getResources().getIdentifier("@drawable/" + "test", "drawable", getPackageName());
    lv.setBackground(getDrawable(context, res));
}
@SuppressWarnings("deprecation")
private Drawable getDrawable(Context context, int im) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        return context.getResources().getDrawable(im, context.getTheme());
    } else {
        return context.getResources().getDrawable(im);
    }
}

     @Override
     public void onClick(View v) {

     } 
}

DB_Resep.java

ContentValues values = new ContentValues();
values.put("_id", "1");
values.put("nama", "Recipe Name");
values.put("bahan", "Random Recipe");
values.put("img", R.drawable.test);
db.insert("resep", "_id", values);

您需要做的所有事情都可以重写适配器类中的getView方法

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {       
        if(convertView == null)
        {
            convertView = inflater.inflate(R.layout.list_row, parent, false);
        }

        //get Image from DB (store path not blob)
        Drawable d = Drawable.createFromPath(pathToImageFile[position]);

       //Set the drawable for view
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
        convertView.setBackground(drawable);
        }
        else{
             convertView.setBackgroundDrawable(drawable);
        }
        /do your remaining stuff....

        return convertView;
    } 

您需要实现自定义适配器而不是SimpleCursorAdapter

这是非常有用的花絮

我已根据您的需求改编了本教程中的代码:

package de.vogella.android.listactivity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public MySimpleArrayAdapter(Context context, String[] values) {
    super(context, -1, values);
    this.context = context;
    this.values = values;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    View view = rowView.findViewById(R.id.background);
    // change the icon for Windows and iPhone
    String s = values[position];
    if (s.startsWith("iPhone")) {
      view.setBackgroundResource(R.drawable.no);
    } else {
      view.setBackgroundResource(R.drawable.ok);
    }

    return rowView;
  }
} 

如果要使用db中的图像资源,请尝试使用以下代码。 我只是检查它是否运作良好,是否运作良好。

int res = getResources().getIdentifier("@drawable/" + YOUR_DB_IMAGE_SURFFIX, "drawable", getPackageName());
listview.setBackground(getDrawable(context, res);

private Drawable getDrawable(Context context, int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        return context.getResources().getDrawable(id, context.getTheme());
    } else {
        return context.getResources().getDrawable(id);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM