知道何时单击checktextiew

时间:2014-06-28 19:28:25

标签: android click

我已动态创建所有已安装应用的checkedtextview。我想知道如何知道用户何时点击checkedtextview。我搜索过,找不到或者不理解解决方案。有人可以举个例子吗?

    ScrollView sv = new ScrollView(this);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);

    final PackageManager pm = getPackageManager();

    List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

    for (ApplicationInfo packageInfo : packages) {
            CheckedTextView ctv = new CheckedTextView(this);
            ctv.setText(packageInfo.packageName);
            ctv.setCheckMarkDrawable (android.R.drawable.checkbox_on_background);
            ctv.setHeight(80);
            ctv.setTextSize(35);
            ll.addView(ctv);
    }
    this.setContentView(sv);

这样做了什么,但似乎不是正确的方法?

for (ApplicationInfo packageInfo : packages) {
            CheckedTextView ctv = new CheckedTextView(this);
            ctv.setText(packageInfo.packageName);
            ctv.setCheckMarkDrawable (android.R.drawable.checkbox_on_background);
            ctv.setHeight(80);
            ctv.setTextSize(35);
            ctv.setOnTouchListener(new OnTouchListener(){
                @Override 
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        // Toggle the checked state of the button 
                        CheckedTextView ctv = (CheckedTextView) v;
                        if (ctv.isSelected()) {
                            ctv.setSelected(false);
                            ctv.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);

                        } else { 
                            ctv.setSelected(true);
                            ctv.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);

                        } 
                    } 
                    return true; 
                } 
            });


            ll.addView(ctv);
    }
    this.setContentView(sv);

1 个答案:

答案 0 :(得分:1)

要注意点击视图的时间,您应该使用OnClickListener

ctv.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View view) {
        Toast.makeText(MyActivity.this, "Click!", Toast.LENGTH_SHORT).show();
    }

});