【发布时间】:2018-02-16 18:44:08
【问题描述】:
来自 android 的新手,我有一个自定义的食品列表视图,其中每个项目都有项目名称、数量和数量。数量是编辑文本,数量是文本视图。最初在金额字段中,我显示一个数量的项目的价格。当用户输入数量(整数)时,我试图将数量乘以数量并在同一文本视图中显示总数量(即 textView 数量) 所以我正在使用 TextWatcher 的 onTextChanged 。
当用户输入我能够接收的数量并与原始数量相乘以获得总量时,但是当我尝试使用 onTextChanged 方法中的 textviewAmount.setText(total amount) 设置它时,它不起作用。
在寻找解决方案时,我遇到了这个this 。它说
“EditText 似乎在重置 onCreateView 中的文本时出现问题”
下面是 我所做的示例代码
片段
public class FoodListFragment extends Fragment {
List<FoodListCell> foodListCells ;
ListView listView ;
HotelApp hotelApp;
FragmentTransaction ft;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
hotelApp = (HotelApp)getActivity().getApplicationContext();
View view = inflater.inflate(R.layout.food_listview,container,false);
Log.d("FoodListActivity" ," onCreate");
foodListCells = new ArrayList<>();
listView = (ListView)view.findViewById(R.id.list_view);
foodListCells.add(new FoodListCell("Diet-Vegetable Soup","75.0"));
foodListCells.add(new FoodListCell("Bean-Bacon ","95.0"));
foodListCells.add(new FoodListCell("Chicken Noodle Soup","75.0"));
FoodListAdopter adapter = new FoodListAdopter(hotelApp, R.layout.foodbox_layout, foodListCells);
listView.setAdapter(adapter);
return view;
}}
采用者
public class MenuAdopter extends ArrayAdapter<FoodListCell> {
Context context;
int resource;
List<FoodListCell> foodListCells;
HotelApp hotelApp;
EditText quantity ;
TextView foodBoxAmt ;
Double finalAmt = 0.0, amtForOne = 0.0;
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
hotelApp = (HotelApp)this.context;
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.foodbox_layout,null);
TextView foodBoxDesc = (TextView) view.findViewById(R.id.foodBoxDesc);
foodBoxAmt = (TextView) view.findViewById(R.id.foodBoxAmt);
Button button = (Button) view.findViewById(R.id.addToCartButton);
quantity = (EditText) view.findViewById(R.id.qnty);
final FoodListCell foodListCell = foodListCells.get(position);
foodBoxDesc.setText(foodListCell.getDesc());
foodBoxAmt.setText("Rs." +foodListCell.getPrice());
amtForOne = Double.parseDouble(foodListCell.getPrice().toString());
quantity.addTextChangedListener(new EditTextListener(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
finalAmt=Double.parseDouble(foodListCell.getPrice().toString())*Double.parseDouble(s.toString());
foodBoxAmt.setText("Rs." +finalAmt.toString());
}}
);
return view;
}}
文本观察器
public class EditTextListener implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}}
感谢您的帮助:)
【问题讨论】:
-
您有任何错误吗?如果是,请提供 logcat。
-
不,我没有收到任何错误
标签: android listview android-edittext textwatcher