Java 带有BaseLayout的ListView仅显示第一项
我正在尝试创建BaseAdapter并将其设置为ListView的适配器 每个元素在适配器中都包含一个按钮和一个文本 这是扩展BaseAdapter的my Components Adapter:Java 带有BaseLayout的ListView仅显示第一项,java,android,baseadapter,Java,Android,Baseadapter,我正在尝试创建BaseAdapter并将其设置为ListView的适配器 每个元素在适配器中都包含一个按钮和一个文本 这是扩展BaseAdapter的my Components Adapter: package com.tuxin.myalcoholist; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewG
package com.tuxin.myalcoholist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IngredientsAdapter extends BaseAdapter {
private List<String> ingredients = new ArrayList<String>();
private final Context context;
public List<String> getItems() {
return this.ingredients;
}
public void add(final String value) {
ingredients.add(value);
notifyDataSetChanged();
}
public IngredientsAdapter(Context context) {
this.context=context;
}
public void updateIngredients(List<String> ingredients) {
this.ingredients=ingredients;
notifyDataSetChanged();
}
@Override
public int getCount() {
return this.ingredients.size();
}
@Override
public String getItem(int position) {
return ingredients.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.ingredient_item,parent,false);
}
Button button = (Button)convertView.findViewById(R.id.ingredient_button);
TextView textView = (TextView)convertView.findViewById(R.id.ingredient_textView);
final String ingredient = this.getItem(position);
textView.setText(ingredient);
return convertView;
}
}
向我们显示您的
component\u item.xml
文件。另外,请确保您在该文件上有一个id为成分按钮的按钮。已更新的主帖子。感谢确保您的上下文不为空。如何初始化适配器?IngredientsAdapter IngredientsAdapter=new IngredientsAdapter(this.getActivity());哎呀。。更新主要职位
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="del"
android:id="@+id/ingredient_button"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ingredient_textView"
/>
</LinearLayout>
addIngredientButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
final String ingredient = ingredientEditText.getText().toString().trim();
if (TextUtils.isEmpty(ingredient)) {
Toast.makeText(getActivity().getApplicationContext(),"ingredient is empty",Toast.LENGTH_LONG).show();
} else {
ingredientsAdapter.add(ingredient);
}
}
});