【问题标题】:how to use an ArrayAdapter in android of custom objects如何在自定义对象的android中使用ArrayAdapter
【发布时间】:2014-12-14 23:42:12
【问题描述】:

如何在 Listview 中使用自定义对象的属性。如果我用字符串列表实现 ArrayAdapter,它在 Listview 中显示良好,但是当我使用自定义对象列表时,它只输出内存地址。

我到现在为止的代码:

ArrayList<CustomObject> allObjects = new ArrayList<>();

allObjects.add("title", "http://url.com"));


  ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, allNews);


        // Assign adapter to ListView
        listView.setAdapter(adapter);


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

                Uri uri = Uri.parse( "http://www.google.com" );
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        });

有一个类似的问题here,但这不是我需要的,因为我只需要在列表视图中显示标题,并且当他们点击提取 url 时。

【问题讨论】:

    标签: android android-arrayadapter


    【解决方案1】:

    ArrayAdapter 显示toString() 方法返回的值,因此您需要在自定义Object 类中覆盖此方法以返回所需的字符串。您还需要至少有一个用于 URL 的 getter 方法,以便您可以在 click 事件中检索它。

    public class NewsObject {
        private String title;
        private String url;
    
        public NewsObject(String title, String url) {
            this.title = title;
            this.url = url;
        }
    
        public String getUrl() {
            return url;
        }
    
        @Override
        public String toString() {
            return title;
        }
        ...
    }
    

    onItemClick() 方法中,position 将是与单击的列表项对应的自定义对象的 ArrayList 中的索引。检索 URL,解析它,然后调用 startActivity()

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsObject item = allNews.get(position);
                String url = item.getUrl();
                Uri uri = Uri.parse(url);
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        });
    

    请注意,我假设您的自定义类是 NewsObject,因为这是您的适配器示例所使用的。

    【讨论】:

      【解决方案2】:

      如果您想使用自定义类的方法,您需要实现一个托管 ArrayAdapter 类...如何创建?

      第一步

      获取您的项目并创建一个新类。然后用ArrayAdapter&lt;YourObject&gt;{} 扩展类并在你需要的属性中声明......我的例子:

      public class Room_Adapter extends ArrayAdapter<Room_Object> {
      
      //Declaration of Atributes
      private ArrayList<Room_Object> Rooms_Array;
      private final Activity context;
      private final ListView lvBuinding;
      

      第二

      为这个类声明一个构造函数,你总是需要一个 Activity 和 ArrayList,如果你需要的话,把它放在其他里面......在我的情况下,我需要 listview......我的例子:

      public Room_Adapter(Activity context, ArrayList<Room_Object> Rooms_Array,ListView lvBuinding) {
          super(context, R.layout.room_layout, Rooms_Array);
      
          this.context = context;
          this.Rooms_Array = Rooms_Array;
          this.lvBuinding = lvBuinding;
      }
      

      super 方法需要您的活动、自定义布局(如果有的话)和您的数组。

      第三

      如果您有自定义行布局,请声明一个静态类或创建一个新类。我的示例有一个静态类:

      public static class Room_View{
      
          //Declaration of Atributes
          TextView RoomName;
          ImageView RoomState;
          TextView NoTroubles;
      
          Button btnRoomRow;
      
          ImageButton btnShowRoomTasks;
          ImageButton btnAddTasks;
      
          RelativeLayout RowLayout;
      }
      

      第四个

      覆盖方法getView。

      @Override
      public View getView(int position, View ConvertView, ViewGroup parent) {
      
          //Declaration of Variables
          Room_View rowView; //Custom static class with controls
          LayoutInflater inflator = context.getLayoutInflater();
      
          if (ConvertView == null) {
              rowView = new Room_View();
              ConvertView = inflator.inflate(R.layout.room_layout,null,true); //Inflate your view with your custom view.
      
      
              rowView.RoomName = (TextView) ConvertView.findViewById(R.id.txtvRoom);
              rowView.RoomState = (ImageView) ConvertView.findViewById(R.id.ivRoomState);
              rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvNoTroubles);
      
              rowView.btnRoomRow = (Button) ConvertView.findViewById(R.id.btnRoomRow);
      
              rowView.btnAddTasks = (ImageButton) ConvertView.findViewById(R.id.btnAddTask);
              rowView.btnShowRoomTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowRoomTasks);
      
              rowView.RowLayout = (RelativeLayout) ConvertView.findViewById(R.id.rowLayout);
      
      
              ConvertView.setTag(rowView);
          }
          else
          {
              rowView = (Room_View) ConvertView.getTag();
          }
      
          //Here custom your control stats
          Room_Object Room = Rooms_Array.get(position);
          rowView.RoomName.setText(Room.getRoomName());
      
          rowView.NoTroubles.setVisibility(View.INVISIBLE);
          rowView.btnShowRoomTasks.setClickable(true);
          rowView.btnShowRoomTasks.setImageResource(R.drawable.list_3a4b66_50);
          rowView.btnShowRoomTasks.setOnClickListener(OnShowTasksClickListener);
      
          //This is for add ClickListiner in my buttons...
          rowView.btnAddTasks.setOnClickListener(OnAddTasksClickListener);
          rowView.btnRoomRow.setOnClickListener(OnAddTasksClickListener);
      
          if(Room.getStatus().equals("Checked")){
              rowView.RowLayout.setBackgroundColor(0xFFC7E6C7);
              rowView.btnShowRoomTasks.setClickable(false);
              rowView.btnShowRoomTasks.setImageResource(R.drawable.list_999999_50);
              rowView.RoomState.setImageResource(R.drawable.check_3ebf4b_50);
          }
          else if(Room.getStatus().equals("Blocked")){
              rowView.RowLayout.setBackgroundColor(0xFFDBC3E5);
              rowView.RoomState.setImageResource(R.drawable.key_9330e0_50);
          }
          else if(Room.getStatus().equals("Dirty")){
              rowView.RowLayout.setBackgroundColor(0xfffceedb);
              rowView.RoomState.setImageResource(R.drawable.icon_housekeeping_3_yellow);
          }
          else if(Room.getStatus().equals("Troubled")){
              rowView.RowLayout.setBackgroundColor(0xFFF4CECD);
              rowView.RoomState.setImageResource(R.drawable.wrench_eb3232_50);
      
              rowView.NoTroubles.setVisibility(View.VISIBLE);
              try {
                  rowView.NoTroubles.setText(Integer.toString(Room.getNoTasks()));
              }
              catch (Exception ex){
                  Log.e("-- Error --",ex.getMessage());
              }
          }
      
          //
          //Pay attention *************************************************
          //
      
          //Now if you needs to use your custom external class this is the site, now imagine that you need gets string from your custom class in the text view, then:
      
          //Declare class
          CustomClass object = new CustomClass();
      
          rowView.(CUSTOM CONTROL FROM YOUR STATIC CLASS).(METHOD OF CONTROL)(object.(CUSTOM METHOD OF YOUR OBJECT));
      
          //For example If you follows my sample then:
          rowView.NoTroubles.setText(object.getNumberOfTroubles().toString);
      
      
          return ConvertView;
      }
      
      //Listener Methods for my button controls
      private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
              int totalRooms = lvBuinding.getCount() - 1;
              int actualRoom = totalRooms - positionSelected;
      
              try{
                  //Your code;
              }
              catch (Exception ex){
                  Log.e("-- CustomError --", ex.getMessage());
              }
          }
      };
      
      private View.OnClickListener OnAddTasksClickListener = new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
              int totalRooms = lvBuinding.getCount() - 1;
              int actualRoom = totalRooms - positionSelected;
      
              try{
                  //Your code;
              }
              catch (Exception ex){
                  Log.e("-- CustomError --", ex.getMessage());
              }
          }
      };
      }
      

      我认为这是您需要的,如果您需要更多信息或相同的建议,我会尽力帮助您...祝您好运,Eduardo!

      【讨论】:

        【解决方案3】:
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        
                        CustomObject obj = allObjects.get(position);
                        //Now use obj to access the property
                        Uri uri = Uri.parse( "http://www.google.com" );
                        startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    }
                });
        

        【讨论】:

          【解决方案4】:

          @mike 答案可能很短。 ArrayAdapter&lt;Item&gt; Item 类应该覆盖 toString()

          @Override
              public String toString() {
                  return name;
              }
          

          你完成了

          【讨论】:

            【解决方案5】:

            您需要覆盖适配器的 getView 以在视图中的某个位置显示单个对象。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-02-12
              • 2013-05-17
              • 1970-01-01
              • 1970-01-01
              • 2016-08-03
              • 2013-10-08
              相关资源
              最近更新 更多