listview onclick吐司无法正常工作

时间:2019-09-12 10:23:54

标签: java android android-fragments android-listview

我在listview fragment中有一个android,我添加了一个onclick事件,无法正常工作。

每当我启动该APP时,它都会给我该应用停止工作的错误。

我关注这篇文章 Can not show Toast in OnItemClickListener inside Fragment 但不为我工作

public class UserFragment extends Fragment implements View.OnClickListener {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    String[] user_listview_item = {"Log In","Sign Up","Fund In","Fund Out","Wallet"};

    View view = inflater.inflate(R.layout.fragment_user, container, false);
    TextView textView = (TextView) view.findViewById(R.id.testing1);


    final ListView user_list_view = (ListView) view.findViewById(R.id.user_listview_id);

    //arayadaptor
    ArrayAdapter<String> ListViewAdapter = new ArrayAdapter<String>(
        getActivity(),
        android.R.layout.simple_list_item_2,
            user_listview_item
    );
    user_list_view.setAdapter(ListViewAdapter);

    user_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getActivity(), user_list_view.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
        }
    });


    textView.setOnClickListener(this);
    return view ;
}



@Override
public void onClick(View view) {

    switch(view.getId()){

        case R.id.testing1:
            Toast.makeText(getActivity(), "Click!", Toast.LENGTH_SHORT).show();
            Log.d("testing1","Result is FAIL 2");
            break;
        default:
            break;
    }

}

感谢进步

1 个答案:

答案 0 :(得分:0)

  

您必须像下面的String Array中一样,从Toast获得一个物品。

user_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getActivity(), user_list_view[i].toString(), Toast.LENGTH_LONG).show();
        }
    });