在自定义数组适配器中更改列表视图的布局

Change the layout of listview in custom array adapter

我正在学习自定义数组适配器,我想做一些事情,比如如果列表视图行视图是 0(列表视图的第一行),我想要一个单独的布局,之后我想要另一个 comoon 布局列表的其余部分。我有自定义适配器,但不太明白,怎么办?。谢谢。

public class NewsFragment extends Fragment{

    private ProgressDialog pDialog;// Progress Dialog
    ListView newsList;
    ArrayList<HashMap<String, String>> postList; //Declare Array
    private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
    GetNews.CustomAdapter CA;

    // JSON Node names
    private static final String TAG_ID = "id";
    private static final String POST_ALLPOSTS = "posts";
    private static final String POST_ID = "ID";
    private static final String POST_TITLE = "post_title";
    private static final String POST_CONTENT = "post_content";
    private static final String GUID = "guid";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.news, container, false);
        newsList = (ListView) view.findViewById(R.id.newsListView);
        TextView topic = (TextView) view.findViewById(R.id.topic);
        postList = new ArrayList<HashMap<String, String>>();
        //Get arguments
        Bundle args = getArguments();
        String mytopic = args.getString("Topic");
        //Set topic
        topic.setText(mytopic.toUpperCase());
        //Execute getContacts
        new GetNews().execute();

        newsList.setOnItemClickListener(new newsListClick());


        return view;
    }

    public class newsListClick implements ListView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d("News List","Clicked " + id);
            android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            SinglePost singleFrag = new SinglePost();
            fragmentTransaction.replace(R.id.content_frame, singleFrag);
            fragmentTransaction.commit();
        }
    }


    //Async Task
    private class GetNews extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            Log.d("Strings","Checking Json");
            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // contacts JSONArray
                    JSONArray posts = null;
                    // Getting JSON Array node
                    posts = jsonObj.getJSONArray(POST_ALLPOSTS);

                    // looping through All Contacts
                    for (int i = 0; i < posts.length(); i++) {

                        JSONObject c = posts.getJSONObject(i);
                        Log.d("Post->",posts.getJSONObject(i).toString());

                        String id = c.getString(POST_ID);

                        Log.d("Post->ID",id);
                        String post_title = c.getString(POST_TITLE);
                        String post_content = c.getString(POST_CONTENT);
                        String guid = c.getString(GUID);
                        Log.d("GUID->",guid);
                        //String gender = c.getString(TAG_GENDER);

                        // tmp hashmap for single post
                        HashMap<String, String> post = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        post.put(POST_ID, id);
                        post.put(POST_TITLE, post_title);
                        post.put(POST_CONTENT, post_content);
                        post.put(GUID, guid);

                        // adding contact to contact list
                        postList.add(post);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        public void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

             // Updating parsed JSON data into ListView
            /*
            ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
                    new String[] { POST_TITLE,POST_CONTENT, GUID },
                    new int[] {R.id.email, R.id.mobile, R.id.guid });
            */

            CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
            newsList.setAdapter(CA);
        }

        public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{

            private final ArrayList<HashMap<String, String>> objects;

            public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
                //something is wrong with super
                super(context, resource, objects);

                this.objects = objects;
            }
            public View getView(int position, View convertView, ViewGroup Parent){

                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item,null);

                }
                TextView thisview = (TextView) convertView.findViewById(R.id.email);
                String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
                if(getListPos == "0"){
                    thisview.setText(getListPos);
                }else{
                    thisview.setText(objects.get(position).get(POST_TITLE));
                }


                //thisview.setText(getListPos);

                return convertView;
            }
        }//

    }
}

试试下面的方法:

public View getView(int position, View convertView, ViewGroup Parent){

if(position==0){
  if(convertView == null){
                 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                 convertView = inflater.inflate(R.layout.first_row_layout,null);

                }
                TextView thisview = (TextView) convertView.findViewById(R.id.email);
                String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
                if(getListPos == "0"){
                    thisview.setText(getListPos);
                }else{
                    thisview.setText(objects.get(position).get(POST_TITLE));
                }

}else{
  if(convertView == null){
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.otherlayout_view,null);

                }
                TextView thisview = (TextView) convertView.findViewById(R.id.email);
                String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
                if(getListPos == "0"){
                    thisview.setText(getListPos);
                }else{
                    thisview.setText(objects.get(position).get(POST_TITLE));
                }
}



                //thisview.setText(getListPos);

                return convertView;
            }

可以使用 getItemViewType 指定列表视图可以拥有的视图类型。 Here 是一些示例。

我做了这样的事情,这是正确的做法吗?它做我想要的事情。

public View getView(int position, View convertView, ViewGroup Parent){
                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item,null);

                }
                TextView thisview = (TextView) convertView.findViewById(R.id.email);
                int getListPos = newsList.getFirstVisiblePosition();
                //i set the count starting 0 and saved in the hashmap array 
                //to compare the first result with the first position of listview
                int count = Integer.parseInt(objects.get(position).get("ListCount"));

                if(getListPos == count) {
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item_header,null);
                    TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
                    TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
                    HeaderText.setText(objects.get(position).get(POST_TITLE));
                    HeaderContent.setText(objects.get(position).get(POST_CONTENT));

                }else{
                    thisview.setText("Normal line");
                }

                return convertView;
            }