如何在片段中实现onclick listview?

时间:2017-12-13 10:20:40

标签: android listview android-fragments

我试图在onClick中提供listview。我在这里使用menu drawermainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        displaySelectedScreen(R.id.nav_item);
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        displaySelectedScreen(item.getItemId());
        return true;
    }

    private void displaySelectedScreen(int itemId) {
        FragmentManager fm = getSupportFragmentManager();

        Fragment Fragment = null;

        switch (itemId) {
            case R.id.nav_item:
                Fragment = new Item();
                break;
            case R.id.nav_do:
                Fragment = new Deliveryorder();
                break;
        }

        if (Fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, Fragment);
            ft.commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }    
}

然后这是我的fragment

之一
public class Item extends Fragment implements View.OnClickListener {
    ListView listView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_item, container, false);
        listView = (ListView) rootView.findViewById(R.id.listView1);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Menu Item");
        getJSON("http://192.168.3.223:84/fppb/andro_login/fppb");
    }

    private void loadIntoListView(String json) throws JSONException {
        List<Itemadapter> items = new ArrayList<Itemadapter>();
        JSONArray jsonArray = new JSONArray(json);
        String[] ba = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            String code     = obj.getString("ItemCode");
            String name     = obj.getString("ItemName");
            String photo    = obj.getString("PhotoName");
            items.add(new Itemadapter(code, name,photo));
        }
       //Toast.makeText(getActivity(), items.toString(), Toast.LENGTH_LONG).show();

        ArrayAdapter<Itemadapter> mArrayAdapter = new ArrayAdapter<Itemadapter>(getActivity(),android.R.layout.simple_expandable_list_item_1,items);
        listView.setAdapter(mArrayAdapter);
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    loadIntoListView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            protected String doInBackground(Void... voids) {

                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;

                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }

                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }

            }
        }

        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }
}

当我运行我的应用并打开Item.java数据显示时,但是当我点击一行时,没有任何事情发生。我已经添加了这个

 @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "TEST", Toast.LENGTH_LONG).show();
    }

我该如何解决?提前谢谢,对不起我的英语。

2 个答案:

答案 0 :(得分:4)

您需要实现一个侦听器:

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

答案 1 :(得分:1)