如何从片段中调用非静态类,或者如何在静态类中调用非静态函数

时间:2019-09-11 08:32:10

标签: android android-listview

我必须将 listview 的适配器类移至主要活动,以便可以访问 viewpager 并通过 view < / p>

但是当我开始从片段中调用此类时,我开始出现错误:

  

错误:包含MainActivity.Adapter的封闭实例是必需的

因为该类不是静态的

这是问题,有什么办法可以解决该错误或替换findViewById()方法吗?

适配器

   public static class Adapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<HelpAdapter> objects;
    String url ;
    private SharedPreferences settings;

    Adapter(Context context, ArrayList<HelpAdapter> products) {

        ctx = context;
        objects = products;

        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    // кол-во элементов
    @Override
    public int getCount() {
        return objects.size();
    }

    // элемент по позиции
    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

    // id по позиции
    @Override
    public long getItemId(int position) {
        return position;
    }

    // пункт списка
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // используем созданные, но не используемые view
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }
        settings = ctx.getSharedPreferences("Settings", ctx.MODE_PRIVATE);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                final TextView textView = view.findViewById(R.id.textView1_2);
                AlertDialog.Builder deleted = new AlertDialog.Builder(ctx);
                deleted.setMessage("Удалить урок?").setCancelable(true).setPositiveButton("Да", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ViewPager viewPager2;
                        MainActivity.PagerAdapter pagerAdapter1;
                        viewPager2 = findViewById(R.id.rager);
                        url = settings.getString("Day","Monday.txt");
                        StringBuffer stringBuffer1 = new StringBuffer();
                        StringBuffer stringBuffer = new StringBuffer();

                        try {
                            FileInputStream read = ctx.openFileInput(url);
                            InputStreamReader reader = new InputStreamReader(read);
                            BufferedReader bufferedReader = new BufferedReader(reader);
                            String temp_read, temp;

                            while ((temp_read = bufferedReader.readLine()) != null) {

                                temp = stringBuffer1.append(temp_read).toString();
                                stringBuffer1.setLength(0);


                                if  (!temp.equals(textView.getText()))
                                    stringBuffer.append(temp_read).append("\n");
                            }

                            bufferedReader.close();
                            reader.close();
                            read.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }



                        try {
                            FileOutputStream write = ctx.openFileOutput(url,ctx.MODE_PRIVATE);

                            write.write(stringBuffer.toString().getBytes());
                            write.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        switch (url) {
                            case "Wednesday.txt" :
                                classWednesday classWednesday = new classWednesday();
                                classWednesday.Start();
                                pagerAdapter1 = new MainActivity.PagerAdapter(new FragmentActivity().getSupportFragmentManager());
                                viewPager2.setAdapter(pagerAdapter1);
                                pagerAdapter1.notifyDataSetChanged();
                                break;


                        }

                    }
                })
                        .setNegativeButton("Нет", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        });
                AlertDialog alertDialog = deleted.create();
                alertDialog.setTitle("Удаление урока");
                alertDialog.show();
            }
        });



        HelpAdapter p = getProduct(position);


        ((TextView) view.findViewById(R.id.textView1)).setText(p.pozic);
        ((TextView) view.findViewById(R.id.textView1_2)).setText(p.name);

        return view;
    }



    HelpAdapter getProduct(int position) {
        return ((HelpAdapter) getItem(position));
    }


}

片段

import static android.content.Context.MODE_PRIVATE;


public class classWednesday extends Fragment {
    private ListView lvMain;
    private List<Fragment> list = new ArrayList<>();
    ArrayList<HelpAdapter> products = new ArrayList<>();
    Integer num = 0;
    private SharedPreferences settings;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && (getActivity()!=null)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("Day","Wednesday.txt" );
            editor.apply();

        }




    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.wednesday, container,false);
        Start();
        lvMain = viewGroup.findViewById(R.id.lvWednesday);
        MainActivity.Adapter adapter = new MainActivity.Adapter(getActivity(),products);
        lvMain.setAdapter(adapter);
        settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
        if (settings.contains("Wednesday")) {
            ImageButton imageButton = viewGroup.findViewById(R.id.imageButtonWednesday);
            if (settings.getBoolean("Wednesday", true))
                imageButton.setImageResource(R.drawable.on);
            else
                imageButton.setImageResource(R.drawable.off);

        }
        return viewGroup;
    }
    public void Start() {
        products.clear();
        try {
            FileInputStream read = getActivity().openFileInput("Wednesday.txt");
            InputStreamReader reader = new InputStreamReader(read);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String temp_read;
            while ((temp_read = bufferedReader.readLine()) != null) {
                num ++;
                products.add(new HelpAdapter(num + ")", temp_read));

            }
            bufferedReader.close();
            reader.close();
            read.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException ignore) {

        }

        num = 0;

    }




}

0 个答案:

没有答案