2017-04-08 47 views
-2

我想用ArrayApapter將文本和圖像添加到TextView。 如果這個北京時間的ArrayAdapter如何將不同類型的視圖添加到ListView中

new ArrayAdapter<View>(getContext(),R.id.element_manual_list, viewsOfPage); 

的定義我可以用一個element_manual_listTextView一個ImageView但我想兩者。我怎樣才能實現這個?或者是否有更簡單的方法將userManual帶圖片的文字寫入Scrollable View? 也許是有風格的HTML

回答

0

您需要創建自己的適配器類:

public class MyAdapter extends ArrayAdapter<User> { 
    public MyAdapter(Context context, ArrayList<User> users) { 
     super(context, 0, users); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // Get the data item for this position 
     User user = getItem(position); 
     // Check if an existing view is being reused, otherwise inflate the view 
     if (convertView == null) { 
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false); 
     } 
     // Lookup view for data population 
     TextView tvName = (TextView) convertView.findViewById(R.id.tvName); 
     ImageView ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto); 
     // Populate the data into the template view using the data object 
     tvName.setText(user.name); 
     ivPhoto.setImageResource(user.photo); 
     // Return the completed view to render on screen 
     return convertView; 
    } 
} 

然後XML爲您排:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<ImageView 
    android:id="@+id/ivPhoto" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@android:drawable/sym_def_app_icon" /> 

<TextView 
    android:id="@+id/tvName" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Name" /> 

然後您的自定義,例如用戶等級:

public class User { 
    public String name; 
    public int photo; 

    public User(String name, int photo) { 
     this.name = name; 
     this.photo = photo; 
    } 
} 

在你的主要clas把這個:

// Construct the data source 
    ArrayList<User> arrayOfUsers = new ArrayList<User>(); 
    // Create the adapter to convert the array to views 
    MyAdapter adapter = new MyAdapter(this, arrayOfUsers); 
    // Attach the adapter to a ListView 
    ListView listView = (ListView) findViewById(R.id.lvItems); 
    listView.setAdapter(adapter); 

    // Add item to adapter 
    User newUser = new User("Nathan", R.drawable.logo); 
    adapter.add(newUser); 
相關問題