列表视图中的中心选定项目

时间:2014-04-03 13:04:03

标签: java android android-listview

你好我想中心当前所选的listview项目。即将项目滚动到列表视图的中心,即使列表视图在单击时有一个项目,它也应该移动到列表视图的中心。

IE当我点击itemclick listner中的项目时,它应该居中当前所选项目。 我的示例代码是

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

    if (civ != null) {

        // civ.setVisibility(View.VISIBLE);
        civ.setBackgroundColor(Color.TRANSPARENT);
    }

    civ = (CustomImageView) view.findViewById(R.id.civ_shelfBook_BookImage);

    BooksAdapter.selectedPosition = position;
    ref.get(civ.getShelfID()).notifyDataSetChanged();
    DetailActivity.shelfID = civ.getShelfID();
    DetailActivity.currentlySelected = position;

    // GeneralModel.actionIntent = new Intent(contex, DetailActivity.class);
    // activity.startActivity(GeneralModel.actionIntent);
    // GeneralModel.actionIntent = null;

    Toast.makeText(contex, "Child Clicked" + civ.shelfID,
            Toast.LENGTH_SHORT).show();
    //

}

1 个答案:

答案 0 :(得分:0)

哟可以做这样的事情..看看我的例子。

此示例包含textview项。单击某个项目时,文本将居中。您可以根据需要修改自定义视图而不是textview

    ListView listView = new ListView(this);
    stringArrayList.add("ONE");
    stringArrayList.add("TWO");
    stringArrayList.add("THREE");
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stringArrayList);
    listView.setAdapter(arrayAdapter);
    setContentView(listView);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        TextView previousView = null; // to hold the previous clicked view
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            TextView textView = (TextView)view.findViewById(android.R.id.text1);
            if(previousView != null) {
                // revert the previous view when a new item is clicked
                previousView.setGravity(Gravity.CENTER_VERTICAL);
            }
            textView.setGravity(Gravity.CENTER);
            previousView = textView;
        }
    });