我正在尝试创建一个包含一些按钮的GridView。按钮正在填充,但是当单击GridView中的Button时,不会调用OnItemClickListener()。
激活类代码
gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ButtonAdapter(getApplicationContext(),answer));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
flipper.showNext();
}
});
自定义按钮适配器
public class ButtonAdapter extends BaseAdapter{
private Context context;
private int[] numbers = new int[100];
private String[] answer;
public ButtonAdapter (Context context,String[] answer){
this.context = context;
this.answer = answer;
for(int i=0;i<100;i++){
numbers[i] = i+1;
}
}
@Override
public int getCount() {
return numbers.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View gridView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(view == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.adapter, null);
} else {
gridView = (View) view;
}
Button button = (Button) gridView.findViewById(R.id.adapter_button);
button.setText(numbers[i]+"");
if(answer[i].equals("null"))
button.setBackgroundColor(context.getResources().getColor(R.color.reset));
else
button.setBackgroundColor(context.getResources().getColor(R.color.optionCheck));
return gridView;
}
}
adapter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/adapter_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
acitvity_layout.xml
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:numColumns="5"
android:columnWidth="50dp"
android:stretchMode="columnWidth"
android:layout_below="@+id/back"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
答案 0 :(得分:0)
您需要实现一个接口,并让您的Activity通过接口侦听器订阅特定按钮。您的ButtonAdapter应该实现onClickListener,但您的Activity应该使用您的自定义方法实现该接口。活动和适配器是两个不同的世界,有两个不同的范围。慢慢浏览这篇文章并遵循其逻辑。它应该让你朝着正确的方向:How to create interface between Fragment and adapter?
适配器与Fragment一起使用的方式与Activity相同。