Android ListView setOnItemClickListener из PopupWindow не вызывается
Я пытаюсь показать ListView из PopupWindow. но когда я пытаюсь вызвать ListView setOnItemClickListener, ничего не делать. Здесь It Java file
PopupWindowActivity.java
public class PopupWindowActivity extends Activity {
String[] data = { "DATA 1", "DATA 2", "DATA 3", "DATA 4", "DATA 5", "DATA 6" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.main, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ListView listView = (ListView) popupView.findViewById(R.id.listView1);
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,data));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
System.out.println("Item Clicked");
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(btnOpenPopup, 20, -5);
}
});
}
}
Вот первый xml файл
a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/openpopup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open Popup Window" />
</LinearLayout>
Здесь он раздувает XML файл
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/recording"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="30sp"
android:layout_marginLeft="30sp"
android:layout_marginRight="30sp"
android:layout_marginTop="100sp" >
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000" >
</ListView>
</RelativeLayout>
</LinearLayout>
Что я делаю неправильно?
Спасибо
Ответы
Ответ 1
Просто одно незначительное изменение в коде и BOOOM, ваш код будет прослушивать ваш список событий click
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
Вы забываете указать настраиваемый параметр true в конструкторе PopupWindow.
Ответ 2
имела ту же проблему, но в моем случае требовалось setFocusble(false)
(и использование ListPopupWindow
не было решением в моем случае, поскольку в работе уже использовалась базовая функциональность PopupWindow
, включая расширение).
Если у кого-то в той же ситуации есть своего рода обходное решение, основанное на ошибке abouton здесь (сообщение # 9)
Основная идея заключается в том, что иерархия ListView
по-прежнему получает события касания, поэтому мы можем запускать вручную onItemClick()
.
Однако этот подход не на 100% идентичен реальной обработке касания ListView
(например, нет свечения выбора при нажатии строки), это очень хорошо для меня на данный момент.
Если у кого-то есть более точное решение этой проблемы, пожалуйста, поделитесь.
Итак, вот полный код Adapter
, который можно использовать с ListView
внутри PopupWindow
, который setFocusable(false)
:
частный класс CustomAdapter расширяет ArrayAdapter {
private LayoutInflater mInflater;
private ListView mOwningListView;
public CustomAdapter(Context context, List<String> objects, ListView listView) {
super(context, android.R.layout.simple_list_item_1, objects);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mOwningListView = listView;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.font_pick_row, null);
}
// this is the key point of workaround
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/*
* as every row is still receiving their touches
* we can use this to manually trigger onItemClick
* since it doesn't firing in popupWindow.setFocusable(false)
*/
mOwningListView.getOnItemClickListener().onItemClick(mOwningListView, v, position, getItemId(position));
}
});
//... other stuff
return convertView;
}
}
Ответ 3
Пусть это поможет вам
.
Объявите listview и список onClickListener вне кнопки ClickListener.