【问题标题】:How to access listview items generated by arrayadapter如何访问由 arrayadapter 生成的列表视图项
【发布时间】:2014-09-09 04:23:10
【问题描述】:

我已将我的应用程序绑定到 Firebase 数据库,并且在能够显示它们之后,我还希望能够选择它们并访问它们的 textview 值。但是 .getValue() 不适用于视图。我知道我的代码非常混乱,我的选择器只能以一种方式工作,但你能帮我找出发生了什么吗?我将添加一个屏幕截图以使事情更清楚。在单击其中一项 int num = Integer.parseInt(text) 时会出现错误,并且应用程序将崩溃,因为我从视图中获得的值是“Android.widget ...”,而不是我想要的. 截图图片:

Orders.java

public class Orders extends ActionBarActivity {
    public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";

// Declare the UI components
    private ListView foodList;

    // Declare an ArrayAdapter that we use to join the data set and the ListView
    // is the way of type safe, means you only can pass Strings to this array
    //Anyway ArrayAdapter supports only TextView
    private ArrayAdapter arrayAdapter;

    private Firebase ref;
    private Orders activ;
    private ArrayList<String> dishes;
    public int total;

@Override
protected void onCreate(Bundle savedInstanceState) {
    activ = this;
    dishes = new ArrayList<String>(20);

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

 // Initialize the UI components
    foodList = (ListView)findViewById(R.id.listView1);

    // Create a reference to a Firebase location
    ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");

    // Read data and react to changes
    ref.addChildEventListener(new ChildEventListener() {
          @Override
          public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
            Map s = snapshot.getValue(Map.class);
            dishes.add(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }

          @Override public void onChildRemoved(DataSnapshot snapshot) {
            Map s = snapshot.getValue(Map.class);
            dishes.remove(snapshot.getName() + "  " + ((Map)snapshot.getValue(Map.class)).get("Price"));
            Log.i("Test", dishes.toString());
            arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());

            // By using setAdapter method, you plugged the ListView with adapter
            foodList.setAdapter(arrayAdapter);
          }

          @Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }

          @Override
          public void onCancelled(FirebaseError arg0) { }
    });

    foodList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            view.setBackgroundColor(Color.GREEN);
            String text = view.toString();
            text.replaceAll("[^\\d.]", "");
            int num = Integer.parseInt(text);
            total += num;
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.orders, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void toPayment(View view) {
    Intent pay = new Intent(this, PaymentMethod.class);
    pay.putExtra(TOTAL_SUM, total);
    startActivity(pay);
}


}

【问题讨论】:

    标签: android listview firebase


    【解决方案1】:

    我从你的问题中了解到:假设当你点击第三个项目,即“pudding 8”时,你想要这个值“pudding 8”(textview 值)。正确的?? 如果是这样,那么您只需要从 ArrayList 中获取值,然后借助 setOnItemClickListener 中的 position 属性首先传递给适配器,如下所示:

    foodList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                view.setBackgroundColor(Color.GREEN);
    
                String text = dishes.get(position);
                // do what you want to do with this value.
    
            }
        });
    

    【讨论】:

    • 当我把你的线路放在那里时,现在我得到一个 NumberFormatException 并保留其余代码。但是我现在设法获得了正确的价值。
    • @Heiki - 上述解决方案仅用于获取您的 STRING VALUE ,如果您将 string(eg:"pudding 8") 转换为整数,它会给您该异常。如果您只需要整数值而不是告诉我,我可以帮助您。
    • text.replaceAll("[^\\d.]", "");对我不起作用。我用 String str = text.substring(text.indexOf(" ")); int num = Integer.parseInt(str.trim());不漂亮,但它有效。
    【解决方案2】:

    像这样改变你的 onClickListener():

    foodList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
            view.setBackgroundColor(Color.GREEN);
            String text = (String)parent.getItemAtPosition(position);
            text.replaceAll("[^\\d.]", "");
            int num = Integer.parseInt(text);
            total += num;
        }
    });
    

    或者您可以使用SimpleAdapter 在单独的xml 布局中使用两个文本视图分别显示字符串和整数值。使用它,您可以更好地获取 onclick() 的值。

    【讨论】:

      【解决方案3】:

      您需要获取该特定视图的文本,view.getText().toString();

      foodList.setOnItemClickListener(new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      
                  view.setBackgroundColor(Color.GREEN);
                  String text = view.getText().toString();
                  text.replaceAll("[^\\d.]", "");
                  int num = Integer.parseInt(text);
                  total += num;
              }
          });
      

      【讨论】:

      • 你不能在视图上调用 .getText(),你只能用 textViews 来做。
      【解决方案4】:

      这可能对你有帮助,但这是不好的方式:

      foodList.setOnItemClickListener(new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      
                  String item = (String) arrayAdapter.getItem(position);
                  String[] split = item.split(" ");
                  int num = Integer.parseInt(split[1]);
                  total += num;
              }
          });
      

      但是很冲动……

      对于我来说,你需要扩展适配器,将你的自定义项目收集到其中,点击后获取它并获取你需要的整数值。

      【讨论】:

        【解决方案5】:

        我知道这可能为时已晚,但希望如此 帮助正在寻找具有多个值的自定义 ArrayAdapter 的类似解决方案的人。

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        
                    ListItems item = (ListItems) parent.getItemAtPosition(position);
                    System.out.println("Item: "+item.getName());
                }
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-22
          • 1970-01-01
          相关资源
          最近更新 更多