【问题标题】:Calling the clickHandler method and passing a value调用 clickHandler 方法并传递一个值
【发布时间】:2010-10-27 11:41:23
【问题描述】:

我有以下微调器代码:

public class MyOnItemSelectedListener implements OnItemSelectedListener {

 public void onItemSelected(AdapterView<?> parent,
     View view, int pos, long id) { 

  String TABLE_NAME = parent.getItemAtPosition(pos).toString();

            int spinnerYearsPos = parent.getSelectedItemPosition();

  Cursor cursor = getStats(TABLE_NAME);           

  showStats(cursor);
 }

 public void onNothingSelected(AdapterView<?> parent) {
   // Do nothing.
 }

}

我想做的是能够将上述代码中的 spinnerYearsPos 变量传递给这个方法:

public void clickHandler(View v ){

  if (v.getId() == R.id.TableTab) {

   Intent myIntent = new Intent(getApplicationContext(), Table.class);


      myIntent.putExtra("spinnerYearsPos", spinnerYearsPos);
       startActivity(new Intent(getApplicationContext(), Table.class));
      }

      if (v.getId() == R.id.OtherStatsTab) {

      startActivity(new Intent(getApplicationContext(), OtherStats.class));

      }

      }  

目前 Eclipse 用红色强调了 spinnerYearsPos 引用。如何调用 clickHandler 方法,然后将 spinnerYearsPos 变量传递给它?

【问题讨论】:

    标签: java android eclipse parameter-passing


    【解决方案1】:

    ///以 spinnerYearsPos 作为全局变量

    int spinnerYearsPos; 
       public class MyOnItemSelectedListener implements OnItemSelectedListener {
    
    
        public void onItemSelected(AdapterView<?> parent,
             View view, int pos, long id) { 
    
          String TABLE_NAME = parent.getItemAtPosition(pos).toString();
    
                    spinnerYearsPos = parent.getSelectedItemPosition();
    
          Cursor cursor = getStats(TABLE_NAME);           
    
          showStats(cursor);
         }
    
         public void onNothingSelected(AdapterView<?> parent) {
           // Do nothing.
         }
    

     public void clickHandler(View v ){
    
          if (v.getId() == R.id.TableTab) {
    
           open_new_act1();
              }
    
              if (v.getId() == R.id.OtherStatsTab) {
    
              startActivity(new Intent(getApplicationContext(), OtherStats.class));
    
              }
    
              }  
    

    ////在处理程序之外的方法下面创建这个

    private void open_new_act1()
    {
    Intent myIntent = new Intent(getApplicationContext(), Table.class);
    
    
          myIntent.putExtra("spinnerYearsPos", spinnerYearsPos);
           startActivity(new Intent(getApplicationContext(), Table.class));
    }
    

    【讨论】:

    • 嗨,Maneesh。非常感谢你。我从你的代码中改变的唯一一点是我用“myIntent”替换了 startActivity 方法中的参数,它工作得很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2021-06-14
    相关资源
    最近更新 更多