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

问题描述:

我目前试图做的是将 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); 
+0

您发布的代码缺少您的适配器的'getView()'。所以我们不知道你在做什么错误,我们不知道这个图像是资源类型,可绘制的还是远程的(图像的HTTP URL)。 – Sufian

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

Here is非常有用的turorial

我已经适应代码本教程为你的需求:

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; 
    } 
} 

所有你需要做的覆盖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; 
    } 
+0

在我的活动中没有可绘制的事件(仅在数据库中),我以编程方式获取所有内容。还有没有其他的wy不使用可直接声明的drawable? –

+0

你想设置背景颜色或图像? – CodingRat

+0

我希望它被设置为在数据库中声明的img –

尝试使用下面的代码,如果你想从数据库使用图像资源。 我只是检查它是否工作正常,它运作良好。

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); 
    } 
} 
+0

什么是V? –

+0

这就是你想要设置为背景的视图 – kimkevin

+0

这将它设置为整个ListView,而不是每个视图的行 –