java - 自定义 ListAdapter 中的点击监听器如何修改列表数据?

标签 java android android-listfragment clicklistener

我正在尝试制作一个相对简单的文件系统浏览器,它可以显示目录并让您选择它们​​。我有一个列表 fragment ,它使用自定义适配器将目录显示为列表。我为列表中的每个条目创建了一个 clickListener。我需要得到它,以便在单击列表条目时刷新整个 ListView 。由于此点击监听器是在我的适配器中定义的,因此它如何以某种方式向列表 fragment 发送信号,以便告诉它刷新适配器使用的数据。非常感谢帮助。

这是我的代码:

PickerFragment.java:

package com.grid.picker;

import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import android.os.Environment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import static android.content.Intent.getIntent;

public class PickerFragment extends ListFragment
{
    private String currentFilesystemPath = "";  // This path does not include the root path
    private int numberOfFolders = 0;
    private List<Folder> folders = new ArrayList<Folder>();


    public PickerFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

    private void tempPopulate()
    {
        folders.add(new Folder("TestFolder", "/test/path"));
    }

    private void populateFolders()
    {

        // Create a new File at the current path
        File currentFolder = new File(Environment.getExternalStorageDirectory().getPath()+currentFilesystemPath);

        Utility.debugOutput("populateFolders() currentFolder: " +currentFolder);

        // Lets get the list of folders
        String[] directories = currentFolder.list(new FilenameFilter() {
            @Override
            public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
            }
        });

        // Build up the list of folders with folder objects
        for(int i=0; i<directories.length;i++)
        {
            //Utility.debugOutput("Folder:" +directories[i].toString());
            folders.add(new Folder(directories[i].toString(), currentFolder.getPath()+directories[i].toString()));
        }


    }

    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);



        // Temporary folder population
        //tempPopulate();
        populateFolders();



        /*
        // Set an adapter for this list fragment to use
        setListAdapter(new ArrayAdapter<Folder>(getActivity(),
                android.R.layout.simple_list_item_activated_1, folders));
        */

        // We want to use our custom adapter. We pass in this activity, the layout to use, and an array of folders
        // We give it a new Folder object just so it knows what type of objects are in the array...??
        FolderAdapter adapter = new FolderAdapter(this.getActivity(), R.layout.listview_item_row, folders.toArray(new Folder[0]));


       // Use our custom adapter for the list
       setListAdapter(adapter);




    }

}

文件夹适配器.java:

package com.grid.picker;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class FolderAdapter extends ArrayAdapter<Folder>
{
    Folder[] folders = null;
    Context context;
    int layoutResourceId;

    // Constructor
    // Param 1: Reference of the activity
    // Param 2: The resource id of the layout file we want to use for displaying each ListView item
    public FolderAdapter(Context context, int layoutResourceId, Folder[] data)
    {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.folders = data;
    }

    // This is a function that the click listener can call to start the list update process
    public void updateList(String name)
    {
        Utility.debugOutput("updateList() rx: " +name);


        this.notifyDataSetChanged();


    }

    // Presumably getView is called for every row in the list ?
    // position is the index of the list item in the list
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        // Create a new view to play with
        View row = convertView;

        final int rowID = position;

        FolderHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            // Inflate (parse) the layout XML
            row = inflater.inflate(layoutResourceId, parent, false);

            //Instantiate a new static object for folder icons (static for speed (caching)
            holder = new FolderHolder();
            holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
            holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

            row.setTag(holder);

            // Set clickListener
            row.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    Utility.debugOutput("Row ID clicked: " +rowID);
                    Utility.debugOutput("Folder array:" +folders[rowID].folderName);
                    updateList(folders[rowID].folderName);
                    //Toast.makeText(context,"you clicked item: "+rowID, Toast.LENGTH_LONG.show();
                    //code you want to execute on click of list item...
                }
            });
        }
        else
        {
            holder = (FolderHolder)row.getTag();
        }

        Folder folder = folders[position];
        holder.txtTitle.setText(folder.folderName);

        holder.txtTitle.setText(folder.folderName);
        holder.imgIcon.setImageResource(folder.icon);

        /*
        // Add click listener to the view
        View.OnClickListener clickListener = new View.OnClickListener() {
            public void onClick(View v) {
                Utility.debugOutput("Something clicked???!");

                // This call requires API level 15 minimum...
                v.callOnClick();
            }
        }; */

        //row.setOnClickListener(clickListener);
        return row;
    }

    // This class will be used as a cache for the folder images
    static class FolderHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
    }
}

文件夹.java:

package com.grid.picker;


public class Folder
{
    // Each instance of this class will be an entry in the folder list
    public String folderName;
    public String fullPath;
    public boolean hasChildren = false; // False by default


    public static final int icon = R.drawable.folder;

    // Constructor
    public Folder(String newName, String newFullPath)
    {
        folderName = newName;
        fullPath = newFullPath;
    }


}

listview_item_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <ImageView android:id="@+id/imgIcon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

    <TextView android:id="@+id/txtTitle"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:textStyle="bold"
        android:textSize="22dp"
        android:textColor="#000000"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

</LinearLayout>

最终我需要在列表中显示的每个文件夹上放置一个复选框,但现在我需要获取它以便可以单击列表中显示的文件夹来刷新显示并更新列表。非常感谢。

最佳答案

在你的点击监听器上使用它

// Set clickListener
    row.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            Utility.debugOutput("Row ID clicked: " +rowID);
            Utility.debugOutput("Folder array:" +folders[rowID].folderName);

            notifyDataSetInvalidated();
        }
    });

关于java - 自定义 ListAdapter 中的点击监听器如何修改列表数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23091671/

相关文章:

java - 使用 GSON 解析带有键和选项卡的 JSON 文件

java - 更改方向导致应用程序崩溃 android.support.v4.app.ListFragment

android - 作为 ViewPager 的一部分更新 ListFragment 中的数据

java - Google Android 应用内购买 "Content Delivery"如何正确传递内容?

java - 如何在已经扩展 Thread 的类中扩展 JFrame

java - 我应该如何使用 EGit 处理多模块 Maven 项目?

Android 设备监视器不显示文件

java - 带有 WebView 的 Cookie

android - ListFragment "content view not yet created"旋转

java - ImplementedVersion 在 exec :java target 中无法访问