将数据从活动传递到片段时出现问题

时间:2017-06-10 07:10:30

标签: java android android-fragments

这是我原来的应用: enter image description here

当我点击按钮将数据从活动传递到片段时,我的应用就变成了这样: enter image description here

我不知道为什么!

我告诉你我的代码!

ACTIVITY_SCROLLABLE_TABS.XML:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
            <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"
            android:onClick="logoutUser"

            />

            </LinearLayout>
           <!-- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/azz"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
                </FrameLayout>-->
        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >
 <!--       <fragment
            android:id="@+id/details_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>-->
    </android.support.v4.view.ViewPager>


</android.support.design.widget.CoordinatorLayout>

活动:

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;
    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);





        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);





            }

        }

        //getMyData();
        Bundle bundle = new Bundle();
        bundle.putString("params", "My String data");
      /*  MyListFragment myObj = new MyListFragment();
        myObj.setArguments(bundle);*/
        Fragment fragment = new MyListFragment();
        fragment.setArguments(bundle);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(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 PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener

{
    private List<Planet> planetList;
    private Context context ;
    ArrayList<Birra> objects;
    public boolean Checked;
    private Integer[] imageId;
    String ciao;
    static PlanetAdapter plAdapter;
    String selState ;
    boolean[] itemChecked;
     ArrayList<Integer> hmmm;
    //MyListner mListener;


    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId,ArrayList<Integer> hm) {
        super(context, R.layout.single_listview_item,planetList);
        //itemChecked = new boolean[planetList.size()];

        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
        this.itemChecked=new boolean[planetList.size()];
        this.hmmm=hm;
       // mListener=(MyListner)context;


    }
    public PlanetAdapter(@NonNull Context context, @LayoutRes int resource,ArrayList<Integer> a) {
        super(context, resource);
        this.hmmm=a;
        System.out.println("ARRAYLIST2:"+hmmm);

    }


  /*  public void setItems(ArrayList<Integer> items) {
        hmmm = items;
        notifyDataSetChanged();

        //System.out.println("HMMM:"+hmmm);

    }*/





    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    @Override
    public void onClick(View v) {

    }



    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
      //  public EditText edit;
        public TextView caratteristica;
        public TextView id;
        public ImageView imageView;
        public Spinner spinner;
        public NumberPicker np;


    }


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

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }


   // static ArrayList<Integer> itemss;






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

        View row = convertView;
        PlanetHolder holder = null;



        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);
            holder.np=(NumberPicker)row.findViewById(R.id.np);
           // iterator.setOnClickListener(this.PlanetHolder);
            holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
            holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
            holder.spinner.setVisibility(View.GONE);


            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();


        }



        final Planet p = planetList.get(position);
        System.out.println("stampato P" + p);
        holder.imageView.setImageResource(imageId[position]);
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText("" + p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.caratteristica.setText(p.getCaratteristica());


        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);




        if (isChecked) {



            holder.spinner.setVisibility(View.VISIBLE);
            holder.np.setVisibility(View.VISIBLE);







        } else {
            holder.chkBox.setChecked(false);
            holder.spinner.setVisibility(View.GONE);
            holder.np.setVisibility(View.GONE);

         }


        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);



        final PlanetHolder finalHolder = holder;
        Planet z=getItem(position);
        System.out.println(z);










        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (finalHolder.chkBox.isChecked()) {

                itemChecked[position]=true;

                    System.out.println("POSITION:"+position);
                    finalHolder.spinner.setVisibility(View.VISIBLE);
                    finalHolder.np.setVisibility(View.VISIBLE);
                    finalHolder.np.setMaxValue(10);
                    finalHolder.np.setMinValue(0);
                    finalHolder.np.setWrapSelectorWheel(true);

                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            getContext(),
                            R.array.country_arrays,
                            android.R.layout.simple_spinner_item);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            finalHolder.spinner.setSelection(position);
                          //  selState = finalHolder.spinner.getSelectedItem().toString();
                         //   p.setQuantità(finalHolder.edit.getText().toString().trim());
                            p.setTipo(finalHolder.spinner.getSelectedItem().toString());

                            System.out.println("p.getTipo()"+p.getTipo());





                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }


                    });
                    finalHolder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                        @Override
                        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                            p.setQuantità2(newVal);
                            System.out.println(p.getQuantità2());
                            SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = states.edit();
                            editor.putInt("finalHolder.picker" + finalHolder.planetName.getText().toString(), finalHolder.np.getId());
                            editor.commit();
                        }
                    });



                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();



                } else {
                    finalHolder.spinner.setVisibility(View.GONE);
                    finalHolder.np.setVisibility(View.GONE);
                    finalHolder.np.setValue(0);


                }

            }
        });




        return row;
    }




    }

SINGLE_LISTVIEW_ITEM.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <CheckBox 
        android:id="@+id/chk_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:orientation="vertical"
        android:layout_weight="1" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/chk_box"
        android:textStyle="bold"
        android:textColor="#000000" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/caratteristica"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/name"
                android:layout_toRightOf="@id/chk_box"
                android:textStyle="italic" />
        </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <TextView
        android:id="@+id/dist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/caratteristica"
        android:layout_toRightOf="@id/chk_box"
        android:textSize="12sp"
        android:textStyle="italic" />
        <TextView
            android:id="@+id/valuta"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:textSize="12sp"
            android:textStyle="italic" />
    </LinearLayout>

        <Spinner
            android:id="@+id/simpleSpinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="50dp"
            android:entries="@array/country_arrays"/>

        <NumberPicker
            android:id="@+id/np"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>
    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:layout_marginRight="5dp"
        android:layout_gravity="center"
        />


</LinearLayout>

2 个答案:

答案 0 :(得分:0)

请格式化代码并删除多余的空行。因为它几乎不可读

不要在onActivityResult中添加片段,但在onCreate中,并在必要时在onActivityResult中设置适配器数据。

所以在onCreate中移动此代码:

Fragment fragment = new MyListFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
transaction.commit();

MyListFragment应该有一个名为refreshlist

的方法

此外,在片段布局中,将背景白色放在xml:

android:background="@android:color/white"

答案 1 :(得分:0)

从适配器的Spinner方法隐藏并显示NumberPickergetView()时出现问题:

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

    ........
    ................

    if (isChecked) {
        holder.spinner.setVisibility(View.VISIBLE);
        holder.np.setVisibility(View.VISIBLE);
    } else {
        holder.chkBox.setChecked(false);
        holder.spinner.setVisibility(View.GONE);
        holder.np.setVisibility(View.GONE);
    }
    ........
    ................
}

似乎Listview项目的布局设计不正常。更新您的single_listview_item.xml版面设计,如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <CheckBox
        android:id="@+id/chk_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="72dp"
        android:layout_height="72dp" 
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"/>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_toRightOf="@id/chk_box"
        android:layout_toLeftOf="@id/ivImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/chk_box"
            android:textStyle="bold"
            android:textColor="#000000"
            android:text="This ia name"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/caratteristica"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/name"
                android:layout_toRightOf="@id/chk_box"
                android:textStyle="italic"
                android:text="This is caratteristica"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/dist"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:textStyle="italic"
                android:text="10"/>
            <TextView
                android:id="@+id/valuta"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:textSize="12sp"
                android:textStyle="italic"
                android:text="$"/>
        </LinearLayout>

        <Spinner
            android:id="@+id/simpleSpinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:entries="@array/country_arrays"
            android:visibility="visible"/>

        <NumberPicker
            android:id="@+id/np"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"/>

    </LinearLayout>
</RelativeLayout>