如何在选中 CheckBox 的情况下添加 ListView 项目以分隔 ArrayList?

How to add ListView items where a CheckBox is selected to separate ArrayList?

我正在开发一个应用程序,我想在其中显示一个 ListView 中所有已安装的应用程序。
我成功了。我的 ListView 中的每个项目都包含一个应用程序名称和一个复选框。我希望每当用户按下 Button 时,CheckBox 为 IsSelected() 的所有应用程序名称都应存储在单独的 ArrayList 中。

我尝试了很多方法,但没有任何效果。
我的代码是:

main_activity.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/container"
    android:layout_height="match_parent"
    tools:context="com.example.pc.fkidshell.Teen5Activity">

    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_weight="1"/>
    <Button
        android:id="@+id/btn_add2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="20dp"
        android:text="Add Selected Apps"
        android:width="170dp"
        android:layout_weight="2"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center_horizontal" />
</FrameLayout>

inflator.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="60dp"
    android:gravity="center"
    android:layout_gravity="center"
    android:orientation="horizontal"
    android:weightSum="2" >
    <TextView
        android:id="@+id/a"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:textColor="#000"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1.7" />

    <CheckBox
        android:id="@+id/b"
        android:layout_width="0dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="0.3"
        android:layout_height="wrap_content" />

</LinearLayout>

Datamodel.java

public class Datamodel {
    public String appname = "";
    private boolean selected;

    public String getAppname() {
        return appname;
    }

    public void setAppname(String appname) {
        this.appname = appname;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean isChecked) {
        this.selected = isChecked;
    }

}

Adapter.java:(在 CheckBox 侦听器中,我使用 "MyApplication.setMyapps(ss);" 将应用程序名称分配给我的全局 class (MyApplication) 变量 ArrayList myapps)

public class Adapter extends BaseAdapter {
    Context _ctx;
    LayoutInflater inflater;
    public ArrayList<Datamodel> data;

    public Adapter(Context c, ArrayList<Datamodel> _arraylist) {
        this._ctx = c;
        this.data = _arraylist;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        inflater = (LayoutInflater) _ctx.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.inflator, parent, false);
        final CheckBox checks = (CheckBox) itemView.findViewById(R.id.b);
        final TextView _setappname = (TextView) itemView.findViewById(R.id.a);
        checks.setChecked(data.get(position).isSelected());

        Datamodel obj = data.get(position);
        _setappname.setText(obj.getAppname());
        checks.setTag(position);

        checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                int getPosition = (Integer) buttonView.getTag();
                Datamodel _obj = data.get(getPosition);
                data.get(position).setSelected(isChecked);
                String ss = _obj.getAppname();
                System.out.println("pos is" + getPosition);
                MyApplication.setMyapps(ss);
            }
        });
        return itemView;
    }
}

Mainactivity.java:

public class Teen5Activity extends Activity
{
    private ListView list;
    ArrayList<Datamodel> res;
    Adapter _adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teen5);

        list = (ListView) findViewById(R.id.list);
        List<PackageInfo> _myapps = getPackageManager().getInstalledPackages(0); //all the list of apps pacakage info stores in _myapps
        res = new ArrayList<Datamodel>();   //new arraylist that contains appname and checkboxes status
        for (int i = 0; i < _myapps.size(); i++)
        {
            PackageInfo p = _myapps.get(i);

            Datamodel _model  = new Datamodel();
            _model.setAppname(p.applicationInfo.loadLabel(getPackageManager()).toString());
            res.add(_model);
            System.out.println("ajajajja" + res.size() + res.get(i).getAppname());
        }
        _adapter = new Adapter(getApplicationContext(), res);
        _adapter.notifyDataSetChanged();
        list.setAdapter(_adapter);
        Button addbtn=(Button) findViewById(R.id.btn_add2);
        addbtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if((MyApplication.getMyapps())==null)
                {
                    Toast.makeText(getApplicationContext(), "Nothing to ADD!", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Successfully Added your Apps!", Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}

MyApplication.java:

public class MyApplication extends Application
{
    private static ArrayList<String> myapps=null;
    public static void setMyapps(String logo)
    {
        myapps.add(logo);
    }
    public static ArrayList<String> getMyapps()
    {
        return myapps;
    }

}

我可以在您的代码中找到以下错误:

1) 您需要初始化您的 MyApplication class 的 myApps arraylist.If 您尝试调用 setMyApps 而不初始化您的 arrayList,您将得到空指针异常。您还需要一个删除方法来动态更新您已检查的应用程序列表。

public class MyApplication extends Application
{
private static ArrayList<String> myapps= new ArrayList<String>();//Create an instance of the list, don't keep it as null

public static void setMyapps(String logo)
{
    myapps.add(logo);
}
public static ArrayList<String> getMyapps()
{
    return myapps;
}
public static void removeApp(String appName)
{
     myapps.remove(appName);
}

}

2) 您需要将其添加到您的列表中, 如果它被选中,而不是 false 状态。因此,每当您访问该列表时,存在的元素指的是 checked applications.Also,您需要 remove 应用程序名称在检查和稍后取消检查的情况下从列表中选择。

 checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            int getPosition = (Integer) buttonView.getTag();
            Datamodel _obj = data.get(getPosition);
            data.get(position).setSelected(isChecked);
            String ss = _obj.getAppname();
            System.out.println("pos is" + getPosition);
            if(isChecked) //Only if the app is checked
                MyApplication.setMyapps(ss);
            else if(MyApplication.getMyApps().contains(ss))
                MyApplication.removeApp(ss);
        }
    });

3) 如果您的 objective 用于存储应用程序名称,我不确定您为什么要从此处的应用程序扩展 MyApplication class。一个简单的字符串数组列表就足够了。

4) 最好通过 程序包名称 而非应用程序名称来跟踪应用程序,因为程序包名称更独特 属性应用

您永远不会检查复选框是否真的被选中,您只会添加项目,而不管复选框是否被选中。

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
    int getPosition = (Integer) buttonView.getTag();
    Datamodel _obj = data.get(getPosition);
    data.get(position).setSelected(isChecked);
    String ss = _obj.getAppname();
    System.out.println("pos is" + getPosition);
    MyApplication.setMyapps(ss);
}

试试

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
    int getPosition = (Integer) buttonView.getTag();
    Datamodel _obj = data.get(getPosition);
    data.get(position).setSelected(isChecked);
    String ss = _obj.getAppname();
    if (isChecked) {
        // TODO: if your apps does not contain 'ss' already {
            MyApplication.setMyapps(ss);
        // }
    } else {
        // TODO: Remove ss from your apps
    }
}

如果您确实需要,您可能可以将 List<DataModel> 存储在您的应用程序中,而不是字符串。

您也可以使用 Set 对象而不是 ArrayList 来防止重复

您可以遍历 ArrayList 和 select isSelected() 为 true 的项目:

ArrayList<String> selectedApps = new ArrayList<String>();
for(Datamodel app : res) {
    if(app.isSelected())
        selectedApps.add(app.getAppname());
}