【问题标题】:Issue with ListviewListview 的问题
【发布时间】:2017-06-13 16:52:19
【问题描述】:

这张照片是我的应用程序启动时(所以是第一次)enter image description here

之后,当我选择 s 文件 XML(带有文件管理器)来获取 id 复选框和选中的复选框时,我得到了这个

enter image description here

为什么?谁能帮帮我?

我给你看我的代码!

活动:

public  class ScrollableTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private Button cazzo;
    //private SQLiteHandler db;
    private SessionManager session;
    private TextView txtName;
    private TextView txtEmail;
    int s;
    String intentt="";
    File file;
    Uri filePath;
    ListView lv;
    ArrayList<Integer> hm=new ArrayList<>();
    String path;
    ArrayList<Planet> planetList=new ArrayList();

    private String myString = "azz";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollable_tabs);


        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        cazzo = (Button) findViewById(R.id.btnLogout);
        txtName = (TextView) findViewById(R.id.name);
        txtEmail = (TextView) findViewById(R.id.numero_telefonico);
        lv=(ListView)findViewById(R.id.listview);





        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        cazzo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });
        //db = new SQLiteHandler(getApplication());


        // session manager
       /* session = new SessionManager(getApplication());

        if (!session.isLoggedIn()) {
            logoutUser();
        }*/

        // Fetching user details from SQLite
 /*       HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        String email = user.get("email");
        String id=user.get("id");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(email);*/

        s = getIntent().getIntExtra("EXTRA_SESSION_ID",0);
        System.out.println("IDDDDDDD" + s);

       // getMyData();
    }



   /* public int getMyData() {
        return s;

    }*/


    private void logoutUser() {
        //session.setLogin(false);

      //  db.deleteUsers();

        // Launching the login activity
       /* Intent intent = new Intent(ScrollableTabsActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();*/
        Intent intent = new Intent();
        intent.setPackage("com.asus.filemanager");
        intent.setType("text/xml");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "LOGOUT"), 1);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        filePath = data.getData();

        path = FilePath.getPath(this, filePath);

        System.out.println("PATH" + path);

        int a=0;
        String status="";
        boolean statuss = false;
        String intenttt= path;

        System.out.println("INTENT:"+intenttt);



        file = new File(intenttt);
        System.out.println("FILE:"+file);

        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document doc = null;
        try {
            doc = dBuilder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Element element = doc.getDocumentElement();
        element.normalize();

        NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element2 = (Element) node;
                //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
                String id = getValue("id", element2);
                a = Integer.parseInt(id);
                status = getValue("status", element2);

                statuss= Boolean.parseBoolean(status);

                System.out.println("XML:" + a);

                hm.add(a);

                System.out.println("AZZ:" + hm);





            }

        }



        Bundle bundle = new Bundle();
        bundle.putIntegerArrayList("oki", hm);

        Fragment fragment = new MyListFragment();
        fragment.setArguments(bundle);


        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.commit();
        System.out.println("PASSATO "+bundle);

    }


    private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }



   /* @Override
    protected void onPause() {
        super.onPause();
        logoutUser();
    }*/

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new MyListFragment(), "PIZZE");
        adapter.addFrag(new SixFragment(), "SIX");
        adapter.addFrag(new FiveFragment(), "TAVOLI");
        adapter.addFrag(new ThreeFragment(), "BEVANDE");
        adapter.addFrag(new FourFragment(), "STAMPA");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new SevenFragment(), "SEVEN");
        adapter.addFrag(new EightFragment(), "EIGHT");
        adapter.addFrag(new NineFragment(), "NINE");
        adapter.addFrag(new TenFragment(), "TEN");


        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(10);
    }
    /*private void logoutUser() {
        SessionManager session;
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        getA.finish();
    }*/


    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

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

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }


}

片段:

public class MyListFragment extends Fragment  /*implements
        CompoundButton.OnCheckedChangeListener, View.OnClickListener*/ {


    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user = "";
    private Spinner spinner;
    String selState;
    EditText cristo;
    private String zao;
    CheckBox ck;
    //private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;
    ArrayList<Integer> hm=new ArrayList<>();
     ArrayList<Integer> strtext;

    ArrayList<Integer>mItems;
    HashMap<Integer,String> ar=new HashMap<>();
    //static String intent;
     File file;
    Uri filePath;
    View a,b;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,


    };

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

        /*Bundle bundle = getArguments();
        if (bundle != null) {
            //String data = bundle.getString("params");
            strtext=bundle.getIntegerArrayList("oki");
            //PlanetAdapter pl=new PlanetAdapter(getContext(),R.layout.single_listview_item,strtext);
            //System.out.println("PARAM:"+data);
        }
*/

/*      try {
            int a=0;
            String status="";
            boolean statuss = false;
            *//*File file = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/ordinazioni/26:Maggio:2017-15:02:40 PM.xml");
            System.out.println("FILE:"+file);*//*
            Intent intent = getActivity().getIntent();
            String intenttt=intent.getData().getPath();



            *//*  file = new File(Environment.getExternalStorageDirectory()
                      .getAbsolutePath() +intenttt);*//*
//          String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            file = new File(intenttt);
            System.out.println("FILE:"+file);

            FileInputStream is = new FileInputStream(file);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(is);

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

            for (int i = 0; i < nList.getLength(); i++) {
                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
                    String id = getValue("id", element2);
                    a = Integer.parseInt(id);
                    status = getValue("status", element2);

                    statuss= Boolean.parseBoolean(status);

                    System.out.println("XML:" + a);

                    hm.add(a);




                    }

                }


        } catch (Exception e) {
            e.printStackTrace();
        }*/





}




    /*private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }*/






    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();



        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();




        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);



        ck=(CheckBox)rootView.findViewById(R.id.chk_box);

        //lv = (ListView)getView().findViewById(R.id.listview);

        Bundle bundle = getArguments();
        if (bundle != null) {
            //String data = bundle.getString("params");
            strtext=bundle.getIntegerArrayList("oki");
            //PlanetAdapter pl=new PlanetAdapter(getContext(),R.layout.single_listview_item,strtext);
            System.out.println("PARAM:"+strtext);
        }



        /*Bundle bundle = getArguments();
        if (bundle != null) {
            //String data = bundle.getString("params");
            strtext=bundle.getIntegerArrayList("oki");
            System.out.println("PARAM:"+strtext);
        }*/


        //lv = (ListView) rootView.findViewById(R.id.listview);
        //ListAdapter listAdapter = new MyListAdapter(getContext());
        //lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);



        return rootView;
    }




    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        lv = (ListView)getView().findViewById(R.id.listview);

        //ck=(CheckBox)getView().findViewById(R.id.chk_box);




        displayPlanetList();






    }



    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        //planetList.clear();
        planetList.add(new Planet(0, "Margherita", "6", "€", "(pomodoro e mozzarella)"));
        planetList.add(new Planet(1,"Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet(2,"Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet(3, "Marinara", "5", "€", "(pomodoro)"));
        planetList.add(new Planet(4,"Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId,strtext) {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String pero="";

                int la=0;

                int pos = lv.getPositionForView(buttonView);

                System.out.println("POS:"+pos);



                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);

                    p.setSelected(isChecked);




                    Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + la + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();
                }



            }

        };

        lv.setAdapter(plAdapter);
    }








    @TargetApi(Build.VERSION_CODES.KITKAT)



    public String showResultTotale2(View v) {



        /*int id=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità2();



            }
        }
        return pizzeOrdinate;*/
        int id=0;
        String pizzeOrdinate="";

        for (int i=0;i<plAdapter.getCount();i++) {
            Planet p=plAdapter.getItem(i);
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità2();



            }
        }
        return pizzeOrdinate;
    }
    public List<Integer> id(View v) {



        int id=0;
        int idd=0;
        String acab="";
        String pizzeOrdinate="";
        List<Integer> urls = new ArrayList<>();
        LinkedList<Integer>azz=new LinkedList<>();


        /*for (Planet p : plAdapter.getBox()) {
            //Planet p=planetList.get(i);
            if (p.isSelected()){

                id=p.getId();

                urls.add(id);
                //azz.add(id);



            }*/
        for (int i=0;i<plAdapter.getCount();i++) {
            Planet p=plAdapter.getItem(i);

            if (p.isSelected()){
                //pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità2();

                id=p.getId();

                urls.add(id);

            }



        }
        return urls;



    }


    public  int showResultTotale(View v) {

        int totalAmount=0;

        /*for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                //int quantitaInt= Integer.parseInt(p.getQuantità() )
                int quantitaInt2=p.getQuantità2();
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt2;
            }
        }*/
        for (int i=0;i<plAdapter.getCount();i++) {
            Planet p=plAdapter.getItem(i);
            if (p.isSelected()){
                //pizzeOrdinate+="\n" + p.getName() + " " +p.getTipo()  + " " +p.getDistance() + "€" + "q.tà :" + p.getQuantità2();

                int quantitaInt2=p.getQuantità2();
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt2;

            }



        }
        return totalAmount;
    }





}

我在其中放置 LISTVIEW 的属性的 XML(膨胀 - FRAGMENT_LIST2):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1"
    android:id="@+id/a"
    android:layout_marginLeft="5dp"


    ><!--android:onClick="showResult"-->
<!--    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:orientation="horizontal" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome"
        android:textSize="20dp"
        android:layout_marginLeft="5dp"
        />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:textColor="@color/lbl_name"
            android:textSize="24dp"
            android:layout_marginLeft="5dp"
            />

    <Button
        android:id="@+id/btnLogout"
        android:layout_width="122dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dip"
        android:background="@color/btn_logut_bg"
        android:text="@string/btn_logout"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp"
        android:layout_marginLeft="5dp"
        />


</LinearLayout>-->

    <TextView
        android:id="@+id/numero_telefonico"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/lbl_name"
        android:textSize="13dp" />

   <ListView
        android:id="@+id/listview"
       android:layout_marginTop="100dp"

       android:layout_width="fill_parent"
        android:layout_height="match_parent">

    </ListView>


<!--    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="showResult"
        android:text="get_answer">
    </Button>-->


    </LinearLayout>

【问题讨论】:

    标签: java android android-layout fragment


    【解决方案1】:

    onActivityResult 中,您将再次创建ListFragment 并添加到容器中。取而代之的是,您可以像这样实现

    public class MyListFragment extends Fragment {
        public void pickAFile() {
           Intent intent = new Intent();
           intent.setPackage("com.asus.filemanager");
           intent.setType("text/xml");
           intent.setAction(Intent.ACTION_GET_CONTENT);
           startActivityForResult(Intent.createChooser(intent, "LOGOUT"), 1);
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
    
           // Update the list here
        }
    }
    

    【讨论】:

    • 您可以将LocalBroadcastActivity发送到Fragment
    • 解决我的问题的另一种方法?有你的想法吗?
    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多