单击ListView Android时,ListView单击计数

时间:2014-11-09 15:42:08

标签: android listview

检查我的代码。并给我一个解决方案。这不起作用.. 我想在ListView上显示点击次数到“tv1”文本字段*

 listv.setOnItemClickListener(new OnItemClickListener() {               
            String selected_ID = "";

            @Override
            public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {

            String name;

            Cursor row = (Cursor) adapter.getItemAtPosition(position);
            selected_ID = row.getString(0);
            name = row.getString(1);

            //ListView Click Count Code         
            int c=0;
            c++;
            tv1.setText(c);

            }

3 个答案:

答案 0 :(得分:1)

在click处理程序之外声明并初始化count变量。在单击处理程序中,您将计数器增加一个。要在文本视图中显示它,您必须将整数转换为文本。

public class MainActivity extends Activity implements View.OnClickListener {

    private TextView countText;

    private int count = 0;

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

        countText = (TextView) findViewById(R.id.countText);

        findViewById(R.id.incButton).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.incButton:
                count++;
                countText.setText(Integer.toString(count));
                break;
        }
    }
}

注意:如果您还需要应用程序记住下次应用程序启动时的数字,您必须将计数变量存储在文件系统上。最明显的方法是使用SharedPreferences为您存储它。如果您也需要,请告诉我。

答案 1 :(得分:0)

首先取int c = 0;超出方法并声明为类级别

像这样

class YourActivity extends Activity{
int c=0;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
             // your code
               listv.setOnItemClickListener(new OnItemClickListener() {               
                String selected_ID = "";

                @Override
                public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {



                c++;
                tv1.setText(c);

                }
});
)

答案 2 :(得分:0)

试试这个

listv.setOnItemClickListener(new OnItemClickListener() {               
            String selected_ID = "";
            private static int c = 0;
            private static int lastClickedItem = -1;

            @Override
            public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            ...

            if(lastClickedItem != position) {
                c = 0;
            }
            c++;
            tv1.setText(c);
            lastClickedItem = position;

        }