如何添加ListView项目选择CheckBox以分隔ArrayList?

时间:2016-11-14 15:59:04

标签: android listview arraylist android-checkbox

我正在开发一个应用程序,我想在ListView中显示所有已安装的应用程序 我成功了。 ListView中的每个项目都包含一个应用程序名称和一个CheckBox。我希望每当用户按下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);”将应用程序名称分配给我的全局类(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;
    }

}

3 个答案:

答案 0 :(得分:0)

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

1)您需要初始化MyApplication类的myApps arraylist。如果您尝试在不初始化arrayList的情况下调用setMyApps,您将获得空指针异常。您还需要一种删除方法来动态更新已检查的应用列表。

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

2)您需要将其添加到列表中,(如果已选中),而不是虚假状态。因此,无论何时访问列表,存在的元素都会引用已检查的应用程序。此外,如果出现以下情况,您需要从列表中删除应用程序名称检查并稍后取消检查案例。

[Api("API Description")]

3)我不确定你为什么要在这里扩展MyApplication类,如果你的目标是存储应用程序名称......一个简单的字符串arraylist就足够了。

4)最好通过包名称跟踪应用程序,而不是应用名称,因为包名称是应用程序的一个更独特的属性。

答案 1 :(得分:0)

您永远不会检查是否实际选中了复选框,您只会添加项目,无论是否选中该复选框。

@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来防止重复

答案 2 :(得分:0)

您可以循环遍历ArrayList并选择isSelected()为true的项目:

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