【问题标题】:How to set listview row clickable only one time in android?如何在android中设置listview行只能点击一次?
【发布时间】:2016-04-04 04:50:36
【问题描述】:

说明: 我的片段中有一个列表视图。当我单击列表视图的其中一行时,它会转到另一个活动。在列表视图中,我从适配器获取数据。 在适配器视图中,我设置了 setOnClick()。

问题是当我多次单击其中一行时,它会打开多个活动。我只想限制一次单击列表视图项上的特定行。

这是我获取列表视图并设置适配器的片段-

public class HomeFragment extends Fragment{
    public HomeFragment() {
    }

    public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
    private static String url = "";

    List<String> lst_key = null;
    List<JSONObject> arr_completed = null;
    List<String> lst_key2 = null;

    List<JSONObject> lst_obj = null;
    List<String> list_status = null;
    ListView completed_listview;
    int PagerLength = 0,exeption_flag=0;

    View rootView;
    private ViewPager pagerRecentMatches;
    private ImageView imgOneSliderRecent;
    private ImageView imgTwoSliderRecent;
    private ImageView imgThreeSliderRecent;
    private ImageView imgFourSliderRecent;
    private ImageView imgFiveSliderRecent;
    private ImageView imgSixSliderRecent;
    private ImageView imgSevenSliderRecent;
    private ImageView imgEightSliderRecent;

    LinearLayout selector_dynamic;
    LinearLayout Recent_header_layout;
    FrameLayout adbar;
    String access_token = "";
    SharedPreferences sharedPreferences;
    int current_pos=0,status_flag=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        findViews();

        selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
        adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
        new AddLoader(getContext()).LoadAds(adbar);

        MainActivity activity = (MainActivity) getActivity();
        access_token = activity.getMyData();

        sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (access_token == null || access_token=="") {
            url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";

        } else {
            editor.putString("access_token", access_token);
            editor.commit();
            url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
        }
        completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);


        Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);

        Recent_header_layout.setVisibility(View.GONE);

        if(!Utils.isNetworkConnected(getContext())){
            dialog_popup();
        }
        else{
            new TabJson().execute();
        }
        pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        return rootView;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private void dialog_popup() {
        final Dialog dialog = new Dialog(getContext());
        DisplayMetrics metrics = getResources()
                .getDisplayMetrics();
        int screenWidth = (int) (metrics.widthPixels * 0.90);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.internet_alert_box);
        dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
        dialog.setCancelable(true);

        Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
        Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);

        btnNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getActivity().finish();
            }
        });
        dialog.show();
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Utils.isNetworkConnected(getContext())){
                    dialog_popup();
                }
                else{
                    dialog.dismiss();
                    new TabJson().execute();
                }
            }
        });
        dialog.show();
    }
    public class TabJson extends AsyncTask<String, String, String> {

        String jsonStr = "";

        @Override
        protected void onPreExecute() {
            Utils.Pdialog(getContext());
        }

        @Override
        protected String doInBackground(String... params) {

            jsonStr = new CallAPI().GetResponseGetMethod(url);
            exeption_flag=0;
            status_flag = 0;
            if (jsonStr != null) {
                try {
                    if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
                        exeption_flag = 1;
                    } else {
                        JSONObject obj = new JSONObject(jsonStr);

                        if (obj.has("status") && !obj.isNull("status")) {
                            if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
                                status_flag = 1;
                            } else {
                                JSONObject data = obj.getJSONObject("data");
                                JSONArray card = data.getJSONArray("cards");

                                PagerLength = 0;
                                lst_obj = new ArrayList<>();
                                list_status = new ArrayList<>();
                                lst_key = new ArrayList<>();
                                lst_key2 = new ArrayList<>();

                                arr_completed = new ArrayList<>();
                                for (int i = 0; i < card.length(); i++) {
                                    JSONObject card_obj = card.getJSONObject(i);
                                    if (card_obj.getString("status").equals("started")) {
                                        PagerLength++;
                                        lst_obj.add(card_obj);
                                        list_status.add(card_obj.getString("status"));
                                        lst_key.add(card_obj.getString("key"));
                                    }
                                    if (card_obj.getString("status").equals("notstarted")) {
                                        PagerLength++;
                                        lst_obj.add(card_obj);
                                        list_status.add(card_obj.getString("status"));
                                        lst_key.add(card_obj.getString("key"));
                                    }
                                    if (card_obj.getString("status").equals("completed")) {
                                        arr_completed.add(card_obj);
                                        lst_key2.add(card_obj.getString("key"));
                                    }
                                }
                            }
                        }
                    }
                }
                catch(JSONException e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Utils.Pdialog_dismiss();

            if (status_flag == 1 || exeption_flag==1) {
                dialog_popup();
            } else {
                Recent_header_layout.setVisibility(View.VISIBLE);

                LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
                adapterTabRecent.notifyDataSetChanged();
                pagerRecentMatches.setAdapter(adapterTabRecent);
                pagerRecentMatches.setCurrentItem(current_pos);


                ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
                CmAdapter.notifyDataSetChanged();
                completed_listview.setAdapter(CmAdapter);
            }
        }
    }

    private void findViews() {

        pagerRecentMatches = (ViewPager) rootView
                .findViewById(R.id.pager_recent_matches);
        imgOneSliderRecent = (ImageView) rootView
                .findViewById(R.id.img_one_slider_recent);
        imgTwoSliderRecent = (ImageView) rootView
                .findViewById(R.id.img_two_slider_recent);
        imgThreeSliderRecent = (ImageView) rootView
                .findViewById(R.id.img_three_slider_recent);
        imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
        imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
        imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
        imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
        imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

}

从服务器加载数据后,它传递给 onPost() 我调用了一个扩展 BaseAdpter 的适配器

这是我的 BaseAdapter

包适配器;

public class ScheduleAdapter extends BaseAdapter{

    private Context context;
    private List<JSONObject> arr_schedule;
    private List<String> arr_matchKey;
    private static LayoutInflater inflater;
    int flag = 0;
    String time="";
    String status="";
    String match_title = "";
    String match_key="";

    public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
        this.context=context;
        this.arr_schedule=arr_schedule;
        this.arr_matchKey=arr_matchKey;
        inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return this.arr_schedule.size();
    }

    @Override
    public Object getItem(int position) {
        return this.arr_schedule.get(position);
    }

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

    private class Holder{
        TextView txt_one_country_name;
        TextView txt_two_country_name;
        TextView txt_venue;
        TextView txtTimeGMT;
        TextView txtDate;
        TextView txtTimeIST;
        ImageView team_one_flag_icon;
        ImageView team_two_flag_icon;
    }

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

        Holder holder=new Holder();
        String[] parts;
        String[] state_parts;
        String[] match_parts;
        Typeface tf=null;
        String winner_team = "";
        String final_Score="";
        String now_bat_team="",team_name="";
        String related_status="";

        if(convertView==null) {

            convertView = inflater.inflate(R.layout.recent_home_layout, null);

            holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
            holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
            holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
            holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
            holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
            holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
            holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
            holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);

            tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");

            holder.txt_one_country_name.setTypeface(tf);
            holder.txt_two_country_name.setTypeface(tf);
            holder.txt_venue.setTypeface(tf);
            holder.txtTimeIST.setTypeface(tf);
            holder.txtTimeGMT.setTypeface(tf);
            holder.txtDate.setTypeface(tf);

            convertView.setTag(holder);
        }
        else{
            holder=(Holder)convertView.getTag();
        }

        try {
            String overs="";
            String wickets_now="";
            String now_runs="";
            String[] over_parts;

            time = "";
            JSONObject mainObj = this.arr_schedule.get(position);

            status = mainObj.getString("status");

            String name = mainObj.getString("short_name");
            String state = mainObj.getString("venue");
            String title = mainObj.getString("title");
            related_status=mainObj.getString("related_name");

            JSONObject start_date = mainObj.getJSONObject("start_date");


            JSONObject teams=null;
            JSONObject team_a=null;
            JSONObject team_b=null;
            String team_a_key="";
            String team_b_key="";
            time = start_date.getString("iso");

            parts = name.split("vs");
            match_parts = title.split("-");
            state_parts = state.split(",");

            int length = state_parts.length;

            flag=0;
            match_title="";
            winner_team="";

            if (!mainObj.isNull("msgs")) {
                JSONObject msgs = mainObj.getJSONObject("msgs");
                winner_team = "";
                if (msgs.has("info")) {
                    winner_team = msgs.getString("info");
                    flag = 1;
                }
            }

            match_title=name+" - "+match_parts[1];

            JSONObject now=null;
            if(mainObj.has("now") && !mainObj.isNull("now")) {
                now = mainObj.getJSONObject("now");
                if (now.has("batting_team")) {
                    now_bat_team = now.getString("batting_team");
                }
                if (now.has("runs")) {
                    if (now.getString("runs").equals("0")) {
                        now_runs = "0";
                    } else {
                        now_runs = now.getString("runs");
                    }
                }

                if (now.has("runs_str") && !now.isNull("runs_str")) {
                    if (now.getString("runs_str").equals("0")) {
                        overs = "0";
                    } else {
                        if(now.getString("runs_str").equals("null")){
                            overs="0";
                        }
                        else{
                            over_parts=now.getString("runs_str").split(" ");
                            overs=over_parts[2];
                        }
                    }
                }
                if (now.has("wicket")) {
                    if (now.getString("wicket").equals("0")) {
                        wickets_now = "0";
                    } else {
                        wickets_now = now.getString("wicket");
                    }
                }
            }
            try {
                if (!mainObj.isNull("teams") && mainObj.has("teams")) {
                    teams = mainObj.getJSONObject("teams");
                    team_a = teams.getJSONObject("a");
                    team_b = teams.getJSONObject("b");
                    team_a_key = team_a.getString("key");
                    team_b_key = team_b.getString("key");

                    JSONArray team_arr = teams.names();
                    JSONObject team_obj;
                    for (int a = 0; a < team_arr.length(); a++) {
                        if (now_bat_team.equals(team_arr.getString(a))) {
                            team_obj = teams.getJSONObject(team_arr.getString(a));
                            if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
                                team_name = team_obj.getString("short_name");
                            }
                        }
                    }
                }
            }
            catch (NullPointerException e){
                e.printStackTrace();
            }

            if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
                if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
                    final_Score="";
                }
                else{
                    final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
                }
            }

            holder.txt_one_country_name.setText(parts[0]);
            holder.txt_two_country_name.setText(parts[1]);

            if(length==1){
                holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                holder.txtTimeGMT.setText(state_parts[0]);
            }
            if(length==2){
                holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);

            }
            if(length==3){
                holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
                holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
            }
            if(length==4){
                holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
                holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
            }

            holder.txtDate.setText(final_Score);
            holder.txtDate.setTypeface(tf, Typeface.BOLD);
            holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            holder.txtTimeIST.setText(winner_team);
            holder.txt_venue.setText(related_status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                match_key = arr_matchKey.get(position);
                MainActivity activity = (MainActivity) context;
                GetValue gv = new GetValue(context);
                gv.setFullUrl(match_key);
                gv.setAccessToken(activity.getMyData());
                gv.execute();
            }
        });

        return convertView;
    }

    @Override
    public boolean isEnabled(int position) {
        return super.isEnabled(position);
    }
}

此适配器将列表行项设置为列表视图。

在 ScheduleAdapter.java 中,我在 convertView 上设置了 onclick(),在其中我调用了一个 GetValue 类,该类只实现一个 Asynctask 来获取数据并调用和意图,然后它会进入一个活动。

表示 HomeFragment->ScheduleAdapter->GetValue->记分卡

这里, HomeFragment 是具有列表视图的片段

ScheduleAdpter 是一个适配器,它将数据设置为驻留在 homefragment 中的列表视图

GetValue 是实现一些重要任务的类,它传递了一个意图并进入一个活动(它作为后台工作)

ScoreCard 是我的活动,它在单击位于 HomeFragment 中的列表视图的行后调用。

请帮我解决这个问题。

【问题讨论】:

  • 在你开始一个新的活动时试试这个。intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  • 我已经实现了一个intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  • 然后试着把它改成这个..看看结果如何。
  • 还有一个建议。您最好从适配器中删除所有解析。适配器仅用于显示数据,而不用于任何类型的解析或计算,因为这会大大降低您的应用程序的速度。在其他地方进行所有解析并将该值传递给适配器..
  • 它打开了两次,但关闭了一次。

标签: android listview


【解决方案1】:

可以在Listview点击中使用flag-isListClicked,在Aysnc任务类-GetValue的onPostexecute方法中设置flag值为false

convertView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(!isListClicked){
            match_key = arr_matchKey.get(position);
            MainActivity activity = (MainActivity) context;
            GetValue gv = new GetValue(context);
            gv.setFullUrl(match_key);
            gv.setAccessToken(activity.getMyData());
            gv.execute();
            isListClicked = true;
        }


    }
});

【讨论】:

  • 你好,当我按下设备后退按钮然后我按下所有禁用的行后进入活动后,默认情况下为什么?
【解决方案2】:

如果您想防止在用户通过触摸发送垃圾邮件时打开多个活动,请在您的 onClick 事件中添加删除该 onClickListener 的操作,以便在第一次按下后监听器将不存在。

【讨论】:

  • 如何以及在哪里,因为我是 android 新手
  • 我不执行请告诉我
【解决方案3】:

简单的方法是您可以使用您在持有人类中获取的那些字段创建 json 对象的模型类。并添加一个布尔字段 isClickable,默认值为 true。现在,当用户第一次按下一行时,您可以将模型类字段 isClickable 设置为 false。现在当用户第二次按下一行时,你会得到一个行的位置,你可以检查 isClickable。这次它会返回 false。

模型类:

public class CountryInfoModel {

  //other fields to parse json object
   private  boolean isClickable; //<- add one more extra field

    public boolean isClickable() {
        return isClickable;
    }

    public void setIsClickable(boolean isClickable) {
        this.isClickable = isClickable;
    }
}

listview 点击执行:

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

                //country_list is your list of model class List<CountryInfo>

                if(country_list.get(position).isClickable())
                {
                    //Perform your logic
                    country_list.get(position).setIsClickable(false);

                }else{
                    //Do nothing : 2nd time click
                }
            }
        });

【讨论】:

  • 你的意思是我的 sceduleAdapter 我应该执行逻辑吗?
  • 您必须执行列表视图单击事件,其中您将适配器设置为列表视图而不是在适配器类中。在完成_listview.setAdapter(CmAdapter)之后的主片段onPostExecute 中的casel;
  • 我如何找到 CountryInfoModel 中的两种方法?
  • 请告诉我怎么做?不懂
  • 您可以创建一个模型类,其中包含您在带有 getter 和 setter 的 json 对象中获取的所有字段。我只解释了需要执行您想要的操作的 1 个字段。搜索如何创建和使用模型类..你会清楚地知道这一点。
【解决方案4】:

尝试为您的列表视图创建自定义点击侦听器并使用它。这样

         public abstract class OnListItemClickListener implements  OnItemClickListener {


         private static final long MIN_CLICK_INTERVAL=600;
         private long mLastClickTime;
         public abstract void onListItemSingleClick(View parent, View view, int position, long id);

         public OnListItemClickListener() {
                 // TODO Auto-generated constructor stub
         }


           @Override
           public void onItemClick(AdapterView<?> parent, View view,  int position, long id) {
                      // TODO Auto-generated method stub
                      long currentClickTime=SystemClock.uptimeMillis();
                      long elapsedTime=currentClickTime-mLastClickTime;

                      mLastClickTime=currentClickTime;

                     if(elapsedTime<=MIN_CLICK_INTERVAL)
                     return;

                     onListItemSingleClick(parent, view, position, id);        

            }

     }

【讨论】:

  • 我们在我的适配器中提供了 onsingleClick() 方法的实现>
  • 创建对象时需要在适配器中写入的内容。
  • 因为我们无法创建抽象类的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2013-01-10
  • 2016-09-11
  • 1970-01-01
  • 2019-11-12
相关资源
最近更新 更多