onitemclick在片段中不起作用(自定义列表视图)

时间:2015-10-07 09:01:08

标签: android android-fragments android-listview

我创建了一个活动来获取数据并将数据显示到自定义列表视图中。

现在我已将此更改为片段,但onItemclick无效。

SiteNews.java

public class SiteNews extends Fragment implements OnTabChangeListener,
        OnPageChangeListener {

    private TabHost tabHost;
    private ViewPager viewPager;
    private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
    int i = 0;
    View v;

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

        v = inflater.inflate(R.layout.tabs_news_layout, container, false);

        // put tabhost here:

        // ***************************** part 1
        // ***************************************************

        i++;

        // init tabhost
        this.initializeTabHost(savedInstanceState);

        // init ViewPager
        this.initializeViewPager();

        // ***************************** part 1
        // ***************************************************

        return v;
    }

    private void initializeViewPager() {
        List<Fragment> fragmentsnews = new Vector<Fragment>();

        fragmentsnews.add(new FragmentAllNews());
        fragmentsnews.add(new FragmentUnreadNews());

        this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
                getChildFragmentManager(), fragmentsnews);
        this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
        this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
        this.viewPager.setOnPageChangeListener(this);

    }

    // fake content for tabhost
    class FakeContent implements TabContentFactory {
        private final Context mContext;

        public FakeContent(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumHeight(0);
            v.setMinimumWidth(0);
            return v;
        }
    }

    private void initializeTabHost(Bundle args) {

        tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
        tabHost.setup();

        for (int i = 1; i <= 2; i++) {

            TabHost.TabSpec tabSpec;
            tabSpec = tabHost.newTabSpec("Tab " + i);
            tabSpec.setIndicator("Tab " + i);
            tabSpec.setContent(new FakeContent(getActivity()));
            tabHost.addTab(tabSpec);
        }
        tabHost.setOnTabChangedListener(this);
    }

    @Override
    public void onTabChanged(String tabId) {
        int pos = this.tabHost.getCurrentTab();
        this.viewPager.setCurrentItem(pos);

        HorizontalScrollView hScrollView = (HorizontalScrollView) v
                .findViewById(R.id.hScrollViewnews);
        View tabView = tabHost.getCurrentTabView();
        int scrollPos = tabView.getLeft()
                - (hScrollView.getWidth() - tabView.getWidth()) / 2;
        hScrollView.smoothScrollTo(scrollPos, 0);

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        this.tabHost.setCurrentTab(position);
    }

}

FragmentAllnews.java

public class FragmentAllNews extends Fragment implements View.OnClickListener {

    ViewGroup v;
    ListView list;
    CustomAdapterAllNews adapter;
    JSONObject json_data;
    JSONArray jArray;
    NewsGetData newsGetData;
    ArrayList<String> id, title_news, text_news, cat_id, status;
    String data, url, msg, check, readnumber, ACTION_SCAN, contents;
    ArrayList<News> newsha;
    News n;
    int sizearray;
    Resources res;
    ArrayList<News> items;
    News ne;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
                container, false);
        list = (ListView) v.findViewById(R.id.listallnews);
        res = getResources();
        createarray();
/*      items = new ArrayList<News>();

        for (int k = 0; k < 25; k++) {
            ne = new News();
            ne.setTitle_news("title_news " + String.valueOf(k));
            ne.setText_news("text_news " + String.valueOf(k));
            ne.setCat_id(k);
            ne.setStatus(k);

            items.add(ne);

        }*/
        ReadData task1 = new ReadData();
        task1.execute(new String[] { "url address" });

        return v;
    }

    private void createarray() {

        id = new ArrayList<String>();
        title_news = new ArrayList<String>();
        text_news = new ArrayList<String>();
        cat_id = new ArrayList<String>();
        status = new ArrayList<String>();
        id.clear();
        title_news.clear();
        text_news.clear();
        cat_id.clear();
        status.clear();

    }

    private class ReadData extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog = new ProgressDialog(getActivity());

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Reading Data...");
            dialog.show();
        }

        String text = "";

        ArrayList<String> list1;

        @Override
        protected Boolean doInBackground(String... urls) {

            url = "php url address";

            InputStream is1;
            for (String url1 : urls) {
                // Read from web to InputStream
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(url);
                    // HttpPost post = new HttpPost(url1);
                    HttpResponse response = client.execute(post);
                    is1 = response.getEntity().getContent();

                } catch (ClientProtocolException e) {
                    Toast.makeText(getActivity(), e.toString(),
                            Toast.LENGTH_LONG).show();
                    return false;
                } catch (IOException e) {
                    Toast.makeText(getActivity(), e.toString(),
                            Toast.LENGTH_LONG).show();
                    return false;
                }
                // end of Read from web to InputStream

                // Convert from InputStream to String Text
                BufferedReader reader;
                try {
                    reader = new BufferedReader(new InputStreamReader(is1,
                            "iso-8859-1"), 8);
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        text += line + "\n";
                    }
                    is1.close();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // end of Convert from InputStream to String Text

                // Convert from Text to JSON and add to ArrayList list1
                list1 = new ArrayList<String>();
                try {
                    JSONArray jArray = new JSONArray(text);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject jsonData = jArray.getJSONObject(i);
                        list1.add(jsonData.getString("title_news") + "   -   "
                                + jsonData.getString("text_news"));
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // end of Convert from Text to JSON and add to ArrayList list1
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result == true) {
                // add list1 to ArrayAdapter
                ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
                        getActivity(), android.R.layout.simple_list_item_1,
                        list1);
                // set adapter into listStudent
                // list.setAdapter(adapter1);
                Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
                data = text;
                newsha = parseJSON3(data);
                adddata(newsha);

            } else {
                Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
                        .show();
            }
            dialog.dismiss();
        }

    }

    /*
     * @Override public void onItemClick(AdapterView<?> parent, View
     * clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
     * int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
     * tv1.getText().toString().substring(0, commaIndex);
     * 
     * Intent in = new Intent(this, EditDataActivity.class);
     * in.putExtra("st_id", st_id); startActivity(in);
     * 
     * }
     */

    public void onItemClick(int mPosition) {

        try {
            News tempValues = (News) newsha.get(mPosition);

            Toast.makeText(getActivity(), tempValues.getText_news(),
                    Toast.LENGTH_LONG).show();

        } catch (Exception e) {

            // Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
        }

    }

    public ArrayList<News> parseJSON3(String result) {
        ArrayList<News> userha = new ArrayList<News>();
        try {
            jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                n = new News();

                n.setId(json_data.getInt("id"));
                id.add(String.valueOf(json_data.getInt("id")));

                n.setTitle_news(json_data.getString("title_news"));
                title_news.add(json_data.getString("title_news"));

                n.setText_news(json_data.getString("text_news"));
                text_news.add(json_data.getString("text_news"));

                n.setCat_id(json_data.getInt("cat_id"));
                cat_id.add(String.valueOf(json_data.getInt("cat_id")));

                n.setStatus(json_data.getInt("status"));
                status.add(String.valueOf(json_data.getInt("status")));

                userha.add(n);
            }
            sizearray = text_news.size();
            if (sizearray <= 0) {
                Toast.makeText(getActivity(), "get data error",
                        Toast.LENGTH_LONG).show();
            } else {

            }

        } catch (JSONException e) {
            // toast(9);
        }
        return userha;
    }

    private void adddata(ArrayList<News> newsha2) {
        adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
        list.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {

    }

}

CustomAdapterAllNews.java

public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {

    /*********** Declare Used Variables *********/
    private Activity activitynews;
    private ArrayList datanews;
    private static LayoutInflater inflaternews=null;
    public Resources resnews;
    News tempValuesnews=null;
    int i=0;
    TableLayout tableLayout1news;
    private List<News> worldpopulationlistnews = null;
    private ArrayList<News> arraylistnews;

    /*************  CustomAdapter Constructor *****************/
    public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {

        /********** Take passed values **********/
        activitynews = a;
        datanews=d;
        resnews = resLocal;
        this.arraylistnews = new ArrayList<News>();
        this.worldpopulationlistnews = worldpopulationlist;
        this.arraylistnews.addAll(worldpopulationlist);
        /***********  Layout inflator to call external xml layout () **********************/
        inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    /******** What is the size of Passed Arraylist Size ************/
    public int getCount() {

        if(datanews.size()<=0)
            return 1;
        return datanews.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    /********* Create a holder to contain inflated xml file elements ***********/
    public static class ViewHolder{

        public TextView text;
        public TextView text1;
        public ImageView image;

    }

    /*********** Depends upon data size called for each row , Create each ListView row ***********/
    @SuppressLint("InflateParams") 

    public View getView(int position, View convertView, ViewGroup parent) {

        View vi=convertView;
        ViewHolder holder;

        if(convertView==null){ 

            /********** Inflate tabitem.xml file for each row ( Defined below ) ************/
            vi = inflaternews.inflate(R.layout.list_news, null); 

            /******** View Holder Object to contain tabitem.xml file elements ************/
            holder=new ViewHolder();
            holder.text=(TextView)vi.findViewById(R.id.textlistnews);
            holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
            holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
           /************  Set holder with LayoutInflater ************/
            vi.setTag(holder);
        }
        else
            holder=(ViewHolder)vi.getTag();

        if(datanews.size()<=0)
        {
            holder.text.setText("No Data");
            holder.text1.setText("نتیجه یافت نشد");
            holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));

        }
        else
        {
            /***** Get each Model object from Arraylist ********/
            tempValuesnews=null;
            tempValuesnews = (News) datanews.get(position);

            /************  Set Model values in Holder elements ***********/
             holder.text.setText(tempValuesnews.getTitle_news());
             holder.text1.setText(tempValuesnews.getText_news());
             holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));

             /******** Set Item Click Listner for LayoutInflater for each row ***********/
             vi.setOnClickListener(new OnItemClickListener(position));
        }
        return vi;
    }

    @Override
    public void onClick(View v) {
            Log.v("CustomAdapter", "=====Row button clicked");
    }

    /********* Called when Item click in ListView ************/
    private class OnItemClickListener  implements OnClickListener{           
        private int mPosition;

        OnItemClickListener(int position){
             mPosition = position;
        }

        @Override
        public void onClick(View arg0) {
        //  FragmentAllNews sct = (FragmentAllNews)activitynews;
      //      Tab1Fragment sct = (Tab1Fragment)activity;
     //     sct.onItemClick(mPosition);
        }               
    }

    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        worldpopulationlistnews.clear();
    if (charText.length() == 0) {
            worldpopulationlistnews.addAll(arraylistnews);
        } 
            else 
        {
            for (News wp : arraylistnews) 
            {
                if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
                        | wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText)) 
                {
                    worldpopulationlistnews.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
}

当我输入此代码时:

    //  FragmentAllNews sct = (FragmentAllNews)activitynews;
  //      Tab1Fragment sct = (Tab1Fragment)activity;
 //     sct.onItemClick(mPosition);
单击

对我不起作用,我需要点击列表视图。

1 个答案:

答案 0 :(得分:1)

不要在适配器中使用v.setOnclicklistener(),最好只在片段中使用,如下所示

list.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        try {

            News tempValues = (News) newsha.get(mPosition);    
            Toast.makeText(getActivity(), tempValues.getText_news(),
            Toast.LENGTH_LONG).show();   

        } catch (Exception e) {    

            // Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();

        }

    }
});