jjzjj

android动态复选框

coder 2023-12-25 原文

我正在尝试动态地将复选框添加到 LinearLayout。我使用了以下代码,

private class ListAdapters extends ArrayAdapter<ApplicationBean> {
private ArrayList<ApplicationBean> items;
private int position;

public ListAdapters(Context context, int textViewResourceId,
        ArrayList<ApplicationBean> mTitleList) {
    super(context, textViewResourceId, mTitleList);
    this.items = mTitleList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    this.position = position;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.applicationlistitem, null);
    }

    final ApplicationBean o = (ApplicationBean) items.get(position);

    if (o != null) {

        txtAppName = (TextView) v.findViewById(R.id.app_name);
        txtAppName.setText("" + o.getAppName());
        launchButton = (Button) v.findViewById(R.id.launch_btn);
        launchButton.setTag(position);
        launchButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                final PackageManager pm = mContext.getPackageManager();
                Intent LaunchIntent = pm
                        .getLaunchIntentForPackage(items
                                .get(Integer.parseInt(v.getTag()
                                        .toString())).getPname());
                mContext.startActivity(LaunchIntent);

            }
        });

        rdgPassFail = (RadioGroup) v.findViewById(R.id.status_group);
        rdgPassFail.setTag(position);

        RadioButton passBtn = (RadioButton) v
                .findViewById(R.id.pass_btn);
        passBtn.setTag(position);
        RadioButton failbtn = (RadioButton) v
                .findViewById(R.id.fail_btn);
        failbtn.setTag(position);

        rdgPassFail
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group,
                            int checkedId) {
                        ApplicationBean o = (ApplicationBean) items
                                .get(Integer.parseInt(group.getTag()
                                        .toString()));

                        switch (checkedId) {
                        case R.id.fail_btn:
                            Log.e("Fail button", "Clicked");
                            o.setFailState(true);
                            o.setPassState(false);
                            numOptions = 0;
                            Log.e("Fail button--1", "Clicked");

                            break;
                        case R.id.pass_btn:
                            Log.e("Pass button", "Clicked");

                            o.setFailState(false);
                            o.setPassState(true);
                            Log.e("Pass button-----1", "Clicked");

                            break;
                        }
                        items.set(Integer.parseInt(group.getTag()
                                .toString()), o);
                    }

                });

            Log.i("checkBoxFlag", "checkBoxFlag not true " + position);
            LinearLayout featuresTable = (LinearLayout) v
                    .findViewById(R.id.failure_reasonslist);


            for (int i = 0; i <= 5; i++) {
                CheckBox feature1 = new CheckBox(this.getContext());
                featuresTable.addView(feature1);
                Log.i("Inside for loop", "creating check box " + position);
            }
            checkBoxFlag = true;

        txtDescription = (EditText) v
                .findViewById(R.id.description_text);
        txtDescription.setTag(position);
        if (txtDescription.isFocused()) {
            InputMethodManager inputManager = (InputMethodManager) mContext
                    .getSystemService(INPUT_METHOD_SERVICE);
            inputManager.restartInput(txtDescription);
        }

        txtDescription
                .setOnFocusChangeListener(new View.OnFocusChangeListener() {

                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (!hasFocus) {

                            final EditText Caption = (EditText) v;
                            o.setDescription(Caption.getText()
                                    .toString());

                        }

                    }
                });
        uninstallButton = (Button) v.findViewById(R.id.uninstall_btn);
        uninstallButton.setTag(position);
        // uninstallButton.setVisibility(View.INVISIBLE);
        o.setUninstallVisible(false);
        uninstallButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri packageUri = Uri.parse("package:"
                        + items.get(
                                Integer.parseInt(v.getTag().toString()))
                                .getPname());
                Intent uninstallIntent = new Intent(
                        Intent.ACTION_DELETE, packageUri);
                uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(uninstallIntent);
                mTitleList.remove(items.get((Integer) v.getTag()));

                mListView.setAdapter(new ListAdapters(mContext,
                        R.id.app_name, mTitleList));
                ((BaseAdapter) mListView.getAdapter())
                        .notifyDataSetChanged();
                isUninstallclicked = true;

            }
        });

        submitButton = (Button) v.findViewById(R.id.submit_btn);
        submitButton.setTag(txtDescription);
        submitButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText tv = (EditText) v.getTag(); // get edittext
                                                        // object

                txtDescription = tv;
                if (txtTesterName.getText().toString().equals("")) {
                    showDialog("Please enter the name of tester",
                            mContext);
                } else if (numOptions == 0) {
                    showDialog("Please select failure reason", mContext);
                } else if (tv.getText().toString().equals("")) {
                    showDialog("Please enter the description", mContext);
                } else if (!isNetworkAvailable()) {

                    showDialog(
                            "No network connection.Report won't be submitted",
                            mContext);
                } else {

                    if (!o.isUninstallVisible()) {
                        uninstallButton.setVisibility(View.VISIBLE);
                        o.setUninstallVisible(true);
                        mListView.invalidate();
                    }
                    PostRequest p = new PostRequest(Integer.parseInt(tv
                            .getTag().toString()));
                    p.execute();

                }
            }

        });

    }
    return v;
}

@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return items.size();
}

}

根据代码, View 中应该有六个复选框。但是当我选中它超过六个复选框时。请在下面找到日志(从 logcat 复制)。日志也来了两次。我在 ListView 中还有一些其他控件。这些在布局 xml 中定义。但是我不能在设计时限制这些复选框的数量。所以我正在尝试动态加载。有人可以帮忙吗?

10:40:23.163: I/Inside for loop(440): creating check box 0
10:40:23.223: I/Inside for loop(440): creating check box 0
10:40:23.223: I/Inside for loop(440): creating check box 0
10:40:23.273: I/Inside for loop(440): creating check box 0
10:40:23.273: I/Inside for loop(440): creating check box 0
10:40:23.303: I/Inside for loop(440): creating check box 0
10:40:23.393: I/c
10:40:23.393: I/Inside for loop(440): creating check box 0
10:40:23.423: I/Inside for loop(440): creating check box 0
10:40:23.423: I/Inside for loop(440): creating check box 0
10:40:23.503: I/Inside for loop(440): creating check box 0
10:40:23.503: I/Inside for loop(440): creating check box 0
10:40:23.553: I/Inside for loop(440): creating check box 0

最佳答案

您必须尝试使用​​以下代码来创建动态复选框

int Array_Count=0;
String[] Str_Array;

Array_Count=Str_Array.length;

LinearLayout my_layout = (LinearLayout)findViewById(R.id.my_layout);

for (int i = 0; i < Array_Count; i++) 
{
    TableRow row =new TableRow(this);
    row.setId(i);
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    CheckBox checkBox = new CheckBox(this);
    checkBox.setOnCheckedChangeListener(this);
    checkBox.setId(i);
    checkBox.setText(Str_Array[i]);
    row.addView(checkBox);  
    my_layout.addView(row);
}

关于android动态复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226353/

有关android动态复选框的更多相关文章

  1. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  2. ruby - 在 Ruby 中动态创建数组 - 2

    有没有办法在Ruby中动态创建数组?例如,假设我想遍历用户输入的书籍数组:books=gets.chomp用户输入:"TheGreatGatsby,CrimeandPunishment,Dracula,Fahrenheit451,PrideandPrejudice,SenseandSensibility,Slaughterhouse-Five,TheAdventuresofHuckleberryFinn"我把它变成一个数组:books_array=books.split(",")现在,对于用户输入的每一本书,我想用Ruby创建一个数组。伪代码来做到这一点:x=0books_array.

  3. ruby - 是否可以将 IRB 提示配置为动态更改? - 2

    我想在IRB中浏览文件系统并让提示更改以反射(reflect)当前工作目录,但我不知道如何在每个命令后进行提示更新。最终,我想在日常工作中更多地使用IRB,让bash溜走。我在我的.irbrc中试过这个:require'fileutils'includeFileUtilsIRB.conf[:PROMPT][:CUSTOM]={:PROMPT_N=>"\e[1m:\e[m",:PROMPT_I=>"\e[1m#{pwd}>\e[m",:PROMPT_S=>"FOO",:PROMPT_C=>"\e[1m#{pwd}>\e[m",:RETURN=>""}IRB.conf[:PROMPT_MO

  4. ruby-on-rails - carrierwave:在序列化动态属性上安装 uploader - 2

    首先,我使用的是rails3.1.3和来自master的carrierwavegithub仓库的分支。我使用after_init钩子(Hook)来确定基于属性的字段页面模型实例并为这些字段定义属性访问器将值存储在序列化哈希中(希望它清楚我是什么谈论)。这是我正在做的事情的精简版:classPage省略mount_uploader命令让我可以访问我想要的属性。但是当我安装uploader时出现错误消息说“nil类的未定义新方法”我在源代码中读到有方法read_uploader和扩展模块中的write_uploader。我如何必须覆盖这些来制作mount_uploader命令使用我的“虚拟

  5. ruby - 在 Ruby 中动态生成多维数组 - 2

    我正在尝试动态构建一个多维数组。我想要的基本上是这样的(为简单起见写出来):b=0test=[[]]test[b]这给了我错误:NoMethodError:undefinedmethod`test=[[],[],[]]而且它工作正常,但在我的实际使用中,我不会事先知道需要多少个数组。有一个更好的方法吗?谢谢 最佳答案 不需要像您正在使用的索引变量。只需将每个数组附加到您的test数组:irb>test=[]=>[]irb>test[["a","b","c"]]irb>test[["a","b","c"],["d","e","f"]]

  6. ruby-on-rails - 使用 gmaps4rails 动态加载谷歌地图标记 - 2

    如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail

  7. ruby-on-rails - 在 Label 标签中嵌套 Ruby on Rails HAML 复选框 - 2

    我有以下不起作用的代码:=form_for(resource,:as=>resource_name,:url=>session_path(resource_name),:html=>{:class=>"well"})do|f|=f.label:email=f.email_field:email=f.label:password=f.password_field:password-ifdevise_mapping.rememberable?%p=f.label:remember_me,:class=>"checkbox"=f.check_box:remember_me,:class=>"

  8. ruby - 动态方法链? - 2

    如何在对象上调用方法名称的嵌套哈希?例如,给定以下哈希:hash={:a=>{:b=>{:c=>:d}}}我想创建一个方法,给定上面的散列,执行以下操作:object.send(:a).send(:b).send(:c).send(:d)我的想法是我需要从一个未知的关联中获取一个特定的属性(这个方法不知道,但程序员知道)。我希望能够指定一个方法链来以嵌套哈希的形式检索该属性。例如:hash={:manufacturer=>{:addresses=>{:first=>:postal_code}}}car.execute_method_hash(hash)=>90210

  9. ruby - 如何使用 method_missing 动态声明方法? - 2

    我有一个ruby​​程序,我想接受用户创建的方法,并使用该名称创建一个新方法。我试过这个:defmethod_missing(meth,*args,&block)name=meth.to_sclass我收到以下错误:`define_method':interningemptystring(ArgumentError)in'method_missing'有什么想法吗?谢谢。编辑:我以不同的方式让它工作,但我仍然很好奇如何以这种方式做到这一点。这是我的代码:defmethod_missing(meth,*args,&block)Adder.class_evaldodefine_method

  10. ruby - 动态扩展现有方法或覆盖 ruby​​ 中的发送方法 - 2

    假设我们有A、B、C类。Adefself.inherited(sub)#metaprogramminggoeshere#takeclassthathasjustinheritedclassA#andforfooclassesinjectprepare_foo()as#firstlineofmethodthenrunrestofthecodeenddefprepare_foo#=>prepare_foo()neededhere#somecodeendendBprepare_foo()neededhere#somecodeendend如您所见,我正在尝试将foo_prepare()调用注入

随机推荐