【问题标题】:If else statement to set different listadaptorif else 语句设置不同的listadaptor
【发布时间】:2013-05-19 17:06:07
【问题描述】:

我正在尝试设置一个 if-else 语句来制作一个带有 JSON 的聊天应用程序,我想让 if-else 语句读取 JSON 并将其放在我希望它们所在的标签中。

想象一下,我是“A”,我和“B”聊天。

如果消息来自“B”(不是我),它会将消息放在列表视图中与右侧对齐的标签上。 ELSE - 当我发送一条消息时,它会放在列表视图内的左侧标签中。

我在语句中使用的字符串是“TAG_FACEBOOK”。

我的列表适配器:

    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item, new String[] { TAG_CONTEXT, TAG_FACEBOOK }, new int[] {
                    R.id.context, R.id.facebook });

setListAdapter(adapter);

我尝试使用这样的 if-else 语句来解决它:

if (TAG_FACEBOOK == "B"){
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item, new String[] { TAG_CONTEXT, TAG_FACEBOOK }, new int[] {
                    R.id.context, R.id.facebook });

    setListAdapter(adapter);
}
else {
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item, new String[] { TAG_CONTEXT, TAG_FACEBOOK }, new int[] {
                    R.id.contextL, R.id.facebookL });

    setListAdapter(adapter);
}

但 Eclipse 告诉我这是“死代码”。 我该怎么办?

【问题讨论】:

  • 您的 if 语句似乎有误,请尝试使用 if (TAG_FACEBOOK.equals("B")),因为这是比较字符串的标准方法。

标签: android json if-statement android-listview


【解决方案1】:

TAG_FACEBOOK == "B" 只比较引用,而不是字符串内容。

使用TAG_FACEBOOK.equals("B")

【讨论】:

    【解决方案2】:

    首先,在 Java 中,您使用以下方法比较两个字符串(s1 和 s2):

    s1.equals(s2)
    

    其次,Eclipse 告诉您它是死代码,因为 TAG_FACEBOOK 是常量。您需要此字符串根据用户是动态的,这样实际上就可以同时访问 if 或 else 块,具体取决于字符串。

    【讨论】:

      【解决方案3】:

      所以像其他人提到的那样使用.equals() 进行字符串比较,但在我看来,您的适配器应该检查应该在屏幕的哪一侧呈现视图(在getView() 内方法)。

      【讨论】:

        【解决方案4】:
        //This is array list
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        
        //Now if-else statement which providing details of list if list is matching then it
        //will to go the activityone if not matching it will go to the activitytwo.
        if (list.size() != 0) {
            Intent intent = new Intent(MainActivity.this, activityone.class);
            intent.putExtra("key", list);
            startActivity(intent);
        } else {
            String string = " ";
            Intent i = new Intent(MainActivity.this, activitytwo.class);
            i.putExtra("key1", string);
            startActivity(i);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-09-14
          • 2015-12-25
          • 2019-04-09
          • 1970-01-01
          • 2016-07-15
          • 2017-02-05
          • 1970-01-01
          相关资源
          最近更新 更多