为了账号安全,请及时绑定邮箱和手机立即绑定

如何在自定义对象的android中使用ArrayAdapter

/ 猿问

如何在自定义对象的android中使用ArrayAdapter

UYOU 2020-02-01 17:11:06

如何在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));

            }

        });

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


查看完整描述

3 回答

?
倚天杖

ArrayAdapter显示toString()方法返回的值,因此您将需要在自定义Object类中重写此方法以返回所需的String。您还需要至少具有该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,因为这是您的Adapter示例所使用的。


查看完整回答
反对 回复 2020-02-01
?
MMTTMM

如果要使用自定义类的方法,则需要实现一个custor ArrayAdapter类...如何创建它?


第一步


获取您的项目并创建一个新类。然后用扩展类,ArrayAdapter<YourObject>{}并在需要的属性内声明...我的示例:


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;

}

超级方法需要您的活动,自定义布局(如果有)和数组。


第三


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


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!


查看完整回答
反对 回复 2020-02-01
?
九州编程

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

            }

        });


查看完整回答
反对 回复 2020-02-01

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信