当前位置: 首页 > 面试题库 >

在每个项目上创建带有onClick侦听器的列表

上官季
2023-03-14
问题内容

我有一个SQLite数据库,我想在ListView中查看所有元素。但我想使每一行都可单击。这该怎么做?这是代码:然后..另一个问题..我有一个活动,可以通过选项菜单启动,它可以从数据库中添加或删除数据。.当我回到此活动时,我想自动更新列表。如何更改代码?

public class WorkflowChoice extends Activity
{
    private static final int INIT_JADE_PROFILE = 0;
    private static final int MANAGE_DATABASE = 1;
    private static final int MODIFY_FILES = 2;
    private static final int CHANGE_THEME = 3;
    private static final int SHOW_OUTPUT_WORKFLOW = 4;
    private LinearLayout properties_container;
    private MyDatabase db;
    TextView wfsTv;
    ListView wfsLv;
    private Cursor c;
    public MyDatabase getDb()
    {
        return db;
    }
    @Override protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choice);
        properties_container = (LinearLayout ) findViewById(R.id.properties_container);
        String host = (String) InitJadeProperties.retrieve(this, getString(R.string.main_container_host), getString(R.string.default_host));
        String port = (String) InitJadeProperties.retrieve(this, getString(R.string.main_container_port), getString(R.string.default_port));
        wfsTv=(TextView)findViewById(R.id.wfsTv);
        ListView wfsLv = (ListView)findViewById(R.id.wfsLv);
        db=new MyDatabase(getApplicationContext());
        db.open();
        //apriamo il db
        if(db.fetchWfs().getCount()==0)
        {
            //inserimento dati, solo se il db è vuoto
            db.insertWf("WF1", "class1");
            db.insertWf("WF2", "class2");
            db.insertWf("WF3", "class3");
            db.insertWf("WF4", "class4");
            db.insertWf("WF5", "class5");
        }
        c=db.fetchWfs();
        // query
        startManagingCursor(c);
        SimpleCursorAdapter adapter=new SimpleCursorAdapter( //semplice adapter per i cursor                 this,                  R.layout.wfs, 
        //il layout di ogni riga/prodotto c,new String[]
        {
            MyDatabase.WfMetaData.ID,MyDatabase.WfMetaData.WF_NAME_KEY,MyDatabase.WfMetaData.WF_CLASS_KEY
        }
        ,//questi colonne 
        new int[]{R.id.IDTv,R.id.nameTv,R.id.classTv }            );
        //in queste views 
        wfsLv.setAdapter(adapter);
        //la listview ha questo adapter //qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview
        int nameCol=c.getColumnIndex(MyDatabase.WfMetaData.WF_NAME_KEY);
        //indici delle colonne
        int classCol=c.getColumnIndex(MyDatabase.WfMetaData.WF_CLASS_KEY);
        if(c.moveToFirst())
        {
            //se va alla prima entry, il cursore non è vuoto         do
            {
                wfsTv.append("Wf Name:"+c.getString(nameCol)+", Class:"+c.getString(classCol)+"\n");
                //estrazione dei dati dalla entry del cursor
            }
            while (c.moveToNext());
            //iteriamo al prossimo elemento
        }
        db.close();
        getWindow().setFormat(PixelFormat.RGBA_8888);
        //visto che usiamo i gradient, usiamo questo trick (vedi snippet forum) getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
        //wfsLv.setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]
        {
            Color.RED,Color.parseColor("#f2bf26")
        }
        ));
        //wfsTv.setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]
        {
            Color.RED,Color.parseColor("#f2bf26")
        }
        ));
        //definizione ed uso di gradient in modo programmatico //animazioni in modo programmatico (vedi snippet forum) Animation a1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        a1.setDuration(1000);
        a1.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.decelerate_interpolator));
        wfsLv.startAnimation(a1);
        //entra da sotto Animation a2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        a2.setDuration(1000);
        a2.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.decelerate_interpolator));
        wfsTv.startAnimation(a2);
        //entra da sopra wfsLv.setClickable(true);
        //e affidiamo la gestione del tap/click ad un apposito listener, che ci permetterà di agire sull’elemento cliccato e ricaricare la nostra lista wfsLv.setOnItemClickListener        (new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<
            ?>
            parent,           View v, int position, long id)
            {
                TextView txtId = (TextView)           v.findViewById(R.id.wfsTv);
                c.requery();
            }
        }
        );
        /*wfsTv.setOnClickListener(new View.OnClickListener()
        {
            @Override         public void onClick(View v)
            {
                CharSequence text = "Workflow scelto!";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(getApplicationContext(), text, duration);
                toast.show();
            }
        }
        );
        */     TextView masterTv = (TextView)findViewById(R.id.masterTv);
        masterTv.setText("Master");
        masterTv.setOnClickListener(new View.OnClickListener()
        {
            @Override         public void onClick(View v)
            {
                startSubActivity();
            }
        }
        );
    }
    private void startSubActivity()
    {
        Intent intent = new Intent(this, ConfigChoice.class);
        startActivity(intent);
    }
}

编辑

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.choice);

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

        String host = (String) InitJadeProperties.retrieve(this, getString(R.string.main_container_host), getString(R.string.default_host));
        String port = (String) InitJadeProperties.retrieve(this, getString(R.string.main_container_port), getString(R.string.default_port));

        wfsTv=(TextView)findViewById(R.id.wfsTv);
        ListView wfsLv = (ListView)findViewById(R.id.wfsLv);

        db=new MyDatabase(getApplicationContext());
        db.open();  //apriamo il db


        if(db.fetchWfs().getCount()==0){//inserimento dati, solo se il db è vuoto

                db.insertWf("WF1", "class1");
                db.insertWf("WF2", "class2");
                db.insertWf("WF3", "class3");
                db.insertWf("WF4", "class4");
                db.insertWf("WF5", "class5");

        }

        c=db.fetchWfs(); // query
        startManagingCursor(c);

        SimpleCursorAdapter adapter=new SimpleCursorAdapter( //semplice adapter per i cursor
                        this, 
                        R.layout.wfs, //il layout di ogni riga/prodotto 
                        c, 
                        new String[]{MyDatabase.WfMetaData.ID,MyDatabase.WfMetaData.WF_NAME_KEY,MyDatabase.WfMetaData.WF_CLASS_KEY},//questi colonne 
                        new int[]{R.id.IDTv,R.id.nameTv,R.id.classTv});//in queste views

        wfsLv.setAdapter(adapter); //la listview ha questo adapter

        adapter.notifyDataSetChanged();
        //qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview

        int nameCol=c.getColumnIndex(MyDatabase.WfMetaData.WF_NAME_KEY);  //indici delle colonne
        int classCol=c.getColumnIndex(MyDatabase.WfMetaData.WF_CLASS_KEY);

        if(c.moveToFirst()){  //se va alla prima entry, il cursore non è vuoto
                do {

                        wfsTv.append("Wf Name:"+c.getString(nameCol)+", Class:"+c.getString(classCol)+"\n"); //estrazione dei dati dalla entry del cursor

                        } while (c.moveToNext());//iteriamo al prossimo elemento
        }

        db.close();
        getWindow().setFormat(PixelFormat.RGBA_8888);   //visto che usiamo i gradient, usiamo questo trick (vedi snippet forum)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);

        //wfsLv.setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{Color.RED,Color.parseColor("#f2bf26")}));
        //wfsTv.setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.RED,Color.parseColor("#f2bf26")}));
        //definizione ed uso di gradient in modo programmatico


        //animazioni in modo programmatico (vedi snippet forum)
        Animation a1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        a1.setDuration(1000);
        a1.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.decelerate_interpolator));
        wfsLv.startAnimation(a1);
        //entra da sotto


        Animation a2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        a2.setDuration(1000);
        a2.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.decelerate_interpolator));
        wfsTv.startAnimation(a2);
        //entra da sopra


        wfsLv.setClickable(true);
        //e affidiamo la gestione del tap/click ad un apposito listener, che ci permetterà di agire sull’elemento cliccato e ricaricare la nostra lista

        wfsLv.setOnItemClickListener
               (new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                  View v, int position, long id) {
         //TextView txtId = (TextView)v.findViewById(R.id.wfsTv); 
         CharSequence text = "Workflow scelto!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(getApplicationContext(), text, duration);
            toast.show();
         c.requery(); 
        }
               });

问题答案:
listview.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
       //---> arg2 <-- will give you row number
       // your code goes here
    }
});

并更改数据

adapter.notifyDataSetChanged();


 类似资料:
  • 问题内容: 我整夜都在绞尽脑汁,但似乎无法完成这一小事情。我想将SwitchPreference添加到我的应用程序的PreferenceActivity中。下面是一张图片。 在我说太多之前,我的问题恰好是这样的:我似乎无法仅在首选项的Switch部分上放置一个侦听器。我可以在首选项上设置onPreferenceTreeClick和onPreferenceClick,如果按文本部分,效果很好。但是,

  • 我有一个关于使用导航组件实现抽屉布局的问题。 我使用Android Studio的包含导航抽屉活动创建了抽屉布局。 实际上,如果菜单项的目的是更改导航XML中定义的片段或活动(如屏幕截图上的程序、歌曲、设置等),那么一切都很好 然而,我也想在“注销”菜单项上执行注销操作,而不启动另一个片段或活动: 我设法做到了: 但我的问题是:使用该方法,所有其他用于工作的项(更改片段)不再工作,因为它调用了Na

  • 好吧,我想强调这一点,并将其全部带入此线程,因为其余线程没有结论性的答案,因此在跳入它们之前,以下是我提到的线程: Adt 不会创建默认的问候世界,但命令行会创建 [已解决]日食在创建新项目/活动时行为不同 过去几天以来,ADT的行为有点古怪。我总是更新我的SDK,所以我经常运行SDK管理器并下载所有更新。最近我注意到,如果我创建一个新的android应用程序项目,它不会创建一个默认的MainAc

  • 我有一个表,其中有多个表项可用。其中,对于某些表项,设置了背景和前景色。 在选择彩色项目时,由于文本颜色为白色,文本很难阅读,因此,我需要将前面的颜色更改为默认颜色,即黑色。我是用选择侦听器完成的 成功地改变了颜色。 但是现在我正在选择任何其他没有着色的项目,所以我想删除上面的选择侦听器并将文本颜色设置为彩色即白色。我不知道如何使用。 有人能帮忙吗?

  • 卸载作为解决方案提供的jdk 9.0.4。有没有办法用NetBeans创建一个Java9项目?

  • 我想在Ubuntu上创建一个项目,但它做不到。不会给我一个错误什么的,只是这个空白屏幕。 帮助/关于: 步骤3-设置环境变量,就像我们在Windows系统中所做的那样,更新您的.bashrc文件并添加以下行 步骤4- 步骤5- 当我将WINDOWS10移动到Ubuntu LTS18.04时,这个问题就已经开始了。 IDE日志(对于stackoverflow太长):https://shrib.com