ListView上的layout_weight导致choiceMode停止工作

时间:2014-10-23 21:50:54

标签: android listview

这段代码是我可以用来说明问题的最小代码(为简洁起见省略了导入)。问题出在ListViews上,如果我将两个ListViews上的layout_weight设置为1,那么页面就会正确布局,但是choiceMode =" singleChoice"无法正确显示(即所选项目不会保持突出显示)。如果layout_weight设置为0或省略,则singleChoice突出显示正常,但屏幕元素在顶部卡在一起。

我无法看到这两者相互影响的合理原因......我倾向于将其称为错误,但对我来说更重要的是如何解决它。

主要布局XML:     

<Button
    android:text="open new Activity"
    android:onClick="openNewActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/test_list"
    android:choiceMode="singleChoice"
    android:listSelector="#abcdef"
    android:layout_weight="1">
 </ListView>

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/second_list"
    android:choiceMode="singleChoice"
    android:listSelector="#abcdef"
    android:layout_weight="1">
</ListView>

<Button
    android:text="open new Activity"
    android:onClick="openNewActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"/>

</LinearLayout>

主要活动代码:

public class MyActivity extends Activity {

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

  @Override
  protected void onPause() {
    super.onPause();
  }

  @Override
  protected void onResume() {
    super.onResume();
    MyData data = new MyData(this);
    Cursor cursor = data.getCursor();

    String[] columns = new String[] {"name"};
    int[] fields = new int[] {R.id.item_text};

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(
      this,
      R.layout.item,
      cursor,
      columns,
      fields,
      0
    );

    ListView lv = (ListView)findViewById(R.id.test_list);
    lv.clearChoices();
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new MyListener(this));
  }

  public void openNewActivity(View v) {
    //
  }

}

点击监听器:

public class MyListener implements AdapterView.OnItemClickListener {

  MyActivity activity;

  public MyListener(MyActivity myActivity) {
    activity = myActivity;
  }

  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    ListView listView = (ListView)activity.findViewById(R.id.second_list);
    MyData data = new MyData(activity);
    Cursor cursor = data.getCursor();

    String[] columns = new String[] {"name"};
    int[] fields = new int[] {R.id.item_text};

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(
      activity,
      R.layout.item,
      cursor,
      columns,
      fields,
      0
    );
    listView.setAdapter(adapter);
  }
}

1 个答案:

答案 0 :(得分:0)

您的listSelector是静态颜色,而不是支持选定和/或激活的状态列表(取决于您支持的版本)