我正在尝试从ListView中单击按钮执行某些操作。 点击按钮即可调用OnClickListener。
这是我的 MainActivity.java
公共类MainActivity扩展了Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView myListView = (ListView) findViewById(R.id.listView);
final Button myButton = (Button) findViewById(R.id.button);
//create the adapter
final rowNumAdapter rownumadapter = new rowNumAdapter(this);
myListView.setAdapter(rownumadapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position==0)
{
Toast.makeText(MainActivity.this,"You just clicked"+ rownumadapter.getItem(position) , Toast.LENGTH_LONG).show();
}
}
});
myButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
rownumadapter.addrows();
}
});
}
}
这是我的 rowNumAdapter.java
公共类rowNumAdapter扩展了BaseAdapter {
private Context mContext;
private int numrows;
public rowNumAdapter(Context context) {
this.mContext=context;
this.numrows= 5;
}
public void addrows()
{
this.numrows+=1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return this.numrows;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Button view = null;
if(convertView == null)
{
view = new Button(this.mContext);
}
else
{
view = (Button)convertView;
}
view.setText(" row " + position);
return view;
}
}
这是我的 activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="10dp"
android:paddingRight="15dp">
<Button
android:layout_marginTop="15dp"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Add View"
android:id="@+id/button"></Button>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false"
>
</ListView>
</LinearLayout>
答案 0 :(得分:1)
您必须使用适配器类中的getView
方法。 Ref
它应该是这样的。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) thisContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = convertView;
// your layout will be here
vi = inflater.inflate(R.layout.activity_main, null);
// Set your button id here
Button btnCheckin = (Button) vi.findViewById(R.id.btnCheckIn);
btnCheckin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("you clicked", "the item at [" + position
+ "] position");
// your button action here.
}
});
}
return vi;
}
Here是关于ListView
和adapters
的好教程。