列表视图<object>适配器的多个toString()

时间:2017-11-10 19:34:35

标签: java android

我需要在对象列表中设置不同的String,具体取决于用户是否属于任何组。我有一个带有Override ToString的Request类,但我需要另一个具有不同返回值的类。我有想法使用参数和switch-case进行toString,但我不知道如何使用参数thru adapter调用toString。

package com.example.krzysztof.mywallet;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.example.krzysztof.DBCorrespondents.AcceptRequest;
import com.example.krzysztof.DBCorrespondents.GetInvites;
import com.example.krzysztof.DBCorrespondents.GetMembers;
import com.example.krzysztof.DBCorrespondents.GetRequests;
import com.example.krzysztof.DBCorrespondents.IgnoreRequest;
import com.example.krzysztof.DBCorrespondents.MemberDelete;
import com.example.krzysztof.Models.Request;
import com.example.krzysztof.Models.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class PendingRequests extends AppCompatActivity {
    Request request;
    RequestQueue queue;
    SharedPreferences sharedPreferences;
    ArrayList <Request> listItems = new ArrayList <> ( );
    ArrayAdapter <Request> adapter;
    ListView listview;


    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_pending_requests );
        listview = ( ListView ) findViewById ( R.id.requestslist );
        adapter = new ArrayAdapter <> ( this,
                android.R.layout.simple_list_item_1,
                listItems );
        listview.setAdapter ( adapter );


        sharedPreferences = getSharedPreferences ( getString ( R.string.PREFERENCES ), Context.MODE_PRIVATE );
        final String GroupId = sharedPreferences.getString ( getString ( R.string.P_GROUPID ), null );
        final String Username= sharedPreferences.getString ( getString ( R.string.P_USERNAME ),null );

        if(GroupId==null)
        {
            Response.Listener <String> responseListener = new Response.Listener <String> ( ) {
                @Override
                public void onResponse ( String response ) {
                    try {
                        JSONArray jsonResponse = new JSONArray ( response );
                        if(jsonResponse.length ()==0)
                        {
                            Context context = getApplicationContext ( );
                            CharSequence text = "Brak zgłoszeń!";
                            int duration = Toast.LENGTH_SHORT;
                            Toast toast = Toast.makeText ( context, text, duration );
                            toast.show ( );
                        }
                        else {
                            for ( int i = 0 ; i < jsonResponse.length ( ) ; i++ ) {
                                JSONObject jsonobject = jsonResponse.getJSONObject ( i );
                                int Id = jsonobject.getInt ( "Id" );
                                String Username = jsonobject.getString ( "Username" );
                                int Status = jsonobject.getInt ( "Status" );
                                String Date = jsonobject.getString ( "Date" );
                                request = new Request ( Id, GroupId, Username, Status, Date );

                                listItems.add ( request );
                                adapter.notifyDataSetChanged ( );
                            }
                        }

                    } catch ( JSONException e ) {
                        e.printStackTrace ( );
                    }
                }
            };
            queue = Volley.newRequestQueue ( PendingRequests.this );
            GetInvites getInvites = new GetInvites ( Username, responseListener );
            queue.add ( getInvites );
            registerForContextMenu ( listview );
        }
        else
        {
            Response.Listener <String> responseListener = new Response.Listener <String> ( ) {
                @Override
                public void onResponse ( String response ) {
                    try {
                        JSONArray jsonResponse = new JSONArray ( response );
                        if(jsonResponse.length ()==0)
                        {
                            Context context = getApplicationContext ( );
                            CharSequence text = "Brak zgłoszeń!";
                            int duration = Toast.LENGTH_SHORT;
                            Toast toast = Toast.makeText ( context, text, duration );
                            toast.show ( );
                        }
                        else {
                            for ( int i = 0 ; i < jsonResponse.length ( ) ; i++ ) {
                                JSONObject jsonobject = jsonResponse.getJSONObject ( i );
                                int Id = jsonobject.getInt ( "Id" );
                                String Username = jsonobject.getString ( "Username" );
                                int Status = jsonobject.getInt ( "Status" );
                                String Date = jsonobject.getString ( "Date" );
                                request = new Request ( Id, GroupId, Username, Status, Date );

                                listItems.add ( request );
                                adapter.notifyDataSetChanged ( );
                            }
                        }

                    } catch ( JSONException e ) {
                        e.printStackTrace ( );
                    }
                }
            };
            queue = Volley.newRequestQueue ( PendingRequests.this );
            GetRequests getRequests = new GetRequests ( GroupId, responseListener );
            queue.add ( getRequests );
            registerForContextMenu ( listview );
        }

    }

    @Override
    public void onCreateContextMenu ( ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo ) {
        super.onCreateContextMenu ( menu, v, menuInfo );
        MenuInflater inflater = getMenuInflater ( );
        inflater.inflate ( R.menu.request_menu, menu );
    }

    @Override
    public boolean onContextItemSelected ( MenuItem item ) {
        AdapterView.AdapterContextMenuInfo info = ( AdapterView.AdapterContextMenuInfo ) item.getMenuInfo ( );
        switch ( item.getItemId ( ) ) {
            case R.id.accept:
                accept ( info );
                return true;
            case R.id.ignore:
                ignore(info);
                return true;
            default:
                return super.onContextItemSelected ( item );
        }
    }

请求类

package com.example.krzysztof.Models;

/**
 * Created by Krzysztof on 10.11.2017.
 */

public class Request {
    private int Id, Status;
    private String Username, GroupId, Date;
    public Request(int Id, String GroupId, String Username, int Status, String Date)
    {
        this.Id=Id;
        this.GroupId=GroupId;
        this.Username=Username;
        this.Status=Status;
        this.Date=Date;
    }

    public int getId () {
        return Id;
    }

    public String getDate () {
        return Date;
    }

    public String getGroupId () {
        return GroupId;
    }

    public int getStatus () {
        return Status;
    }

    public String getUsername () {
        return Username;
    }

    @Override
    public String toString () {
        return this.Username+" wysłał prośbę o dołączenie";
    }
}

1 个答案:

答案 0 :(得分:1)

为此,您必须创建自定义项目渲染视图并创建列表项适配器。

有一个例子,你可以如何实现:

Custom Adapter for List View

在这种情况下,您可以使用解决方案

创建一个如下所示的适配器子类:

public class RequestListAdapter extends ArrayAdapter<Request> {

ArrayList<Request> requests;
public RequestListAdapter(Context context, ArrayList<Request> requests) 
{
    super(context, 0, requests);
    this.requests = requests;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    // Get the data item for this position
    Request request = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.request_list_view_item, parent, false);
    }

    TextView textView = (TextView) 
    convertView.findViewById(R.id.textView);
    textView.setText(request.customLabel());

    return convertView;
  }

}

在布局目录中创建request_list_view_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="10dp"
   android:orientation="horizontal">
   <TextView
    android:id="@+id/tvHome"
    android:textSize="22dp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="HomeTown"
    android:gravity="right" />
  </LinearLayout>

所以更改你的Request类并将你的switch case放在customText方法中:

public class Request {
private int Id, Status;
private String Username, GroupId, Date;
public Request(int Id, String GroupId, String Username, int Status, String Date)
{
    this.Id=Id;
    this.GroupId=GroupId;
    this.Username=Username;
    this.Status=Status;
    this.Date=Date;
}

public int getId () {
    return Id;
}

public String getDate () {
    return Date;
}

public String getGroupId () {
    return GroupId;
}

public int getStatus () {
    return Status;
}

public String getUsername () {
    return Username;
}

public String customLabel(){
   //write your code and switch case here
}

@Override
public String toString () {
    return this.Username+" wysłał prośbę o dołączenie";
}
}

使用这些代码,如下所示:

    //define this array list globally
    ArrayList<Request> requests = new ArrayList<Request>();

    RequestListAdapter adapter = new RequestListAdapter(this.getContext(),requests);

    // Attach the adapter to a ListView
    ListView listView = (ListView) findViewById(R.id.tagListView);
    listView.setAdapter(adapter);

    //add received request from responseListener callback
    requests.add(request)
    adapter.notifyDataSetChanged ( );