-3

I created a ListView with an Activity; but I need to create a ListView with a Fragment.

Here is a screenshot of my Activity:

enter image description here

And this is the corresponding code:

public class Main extends ActionBarActivity implements
        android.widget.CompoundButton.OnCheckedChangeListener {

    ListView lv;
    ArrayList<Planet> planetList;
    PlanetAdapter plAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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


    }

    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", 6, "€"));
        planetList.add(new Planet("Diavola", 7,"€"));
        planetList.add(new Planet("Bufalina", 5,"€"));
        planetList.add(new Planet("Marinara", 5,"€"));
        planetList.add(new Planet("Viennese", 4,"€"));

        plAdapter = new PlanetAdapter(planetList, this);
        lv.setAdapter(plAdapter);
    }

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

        int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            /*Toast.makeText(
                    this,
                    "Clicked on Planet: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
        }

    }
    public void showResult(View v) {
        String result = "Selected Product are :";
        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.selected){
                result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
                //if (p.quantità.equals("") && p.quantità.equals(null) ){
                System.out.println("leggo questo record:"+p.name + " " + p.distance + " " + p.quantità );

                System.out.println("leggo questo p.getquatità :"+p.quantità );
                //}
                //else{
                    System.out.println("leggo questo in p.quantità: "+p.getQuantità());
                    int quantitaInt= Integer.parseInt(p.getQuantità() );
                    totalAmount+=p.distance * quantitaInt;
                //}
            }
        }
//      Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
        //Integer.toString(totalAmount);
        Intent i = new Intent(Main.this, SecondActivity.class);
        i.putExtra("NomeDati1", result);
        i.putExtra("NomeDati2", String.valueOf(totalAmount));
        startActivity(i);

    }
}

class Planet {

    String name;
    int distance;
    String quantità;
    String valuta;
    boolean selected = false;



    public Planet(String name, int distance, String quantità) {
        super();
        this.name = name;
        this.distance = distance;
        this.quantità = quantità;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance = distance;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public String getQuantità() {
        return quantità;
    }

    public void setQuantità(String quantità) {
        this.quantità = quantità;
    }
    public String getValuta() {
        return valuta;
    }

    public void setValuta(String valuta) {
        this.valuta = valuta;
    }

}

public class PlanetAdapter extends ArrayAdapter<Planet>{

    private List<Planet> planetList;
    private Context context;
    ArrayList<Planet> objects;


    public PlanetAdapter(List<Planet> planetList, Context context) {
        super(context, R.layout.single_listview_item, planetList);
        this.planetList = planetList;
        this.context = context;
    }

    public  class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public CheckBox chkBox;
        public EditText edit;
        public String quantità;



    }

    @Override
    public View getView(int position, View convertView, 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.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.edit = (EditText) row.findViewById(R.id.editText);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            row.setTag(holder);
        } else {
            holder = (PlanetHolder) row.getTag();
        }
        final Planet p = planetList.get(position);

        holder.chkBox.setOnCheckedChangeListener((Main) context);
        final PlanetHolder finalHolder = holder;
        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    finalHolder.edit.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            p.setQuantità(finalHolder.edit.getText().toString().trim());
                        }
                    });
                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText(null);
                }
            }
        });
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.edit.setEnabled(false);

        return row;
    }


    ArrayList<Planet> getBox() {
        ArrayList<Planet> box = new ArrayList<Planet>();
        for (Planet p : planetList) {
            if (p.selected)
                box.add(p);
        }
        return box;
    }


}

MAIN.XML:

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="400dp">

    </ListView>
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="showResult"
        android:text="get_answer">
    </Button>


</LinearLayout>

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" />

    <TextView
        android:id="@+id/dist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_toRightOf="@id/chk_box"
        android:textSize="12sp"
        android:textStyle="italic" />
    <EditText
        android:layout_width="196dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editText"
        android:hint="quantità"
        >
    </EditText>
    </LinearLayout>

</LinearLayout>

3 Answers3

1

I strongly suggest go with RecyclerView instead of ListView. For your question you can create listview in fragment similar to activity itself.
you need to put your activity code in fragment and load fragment in activity

Activity xml should look like this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"  android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" ></LinearLayout>

fragment xml should look like this

<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="match_parent"
>


<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</RelativeLayout>

you activity should look like this

public class Main extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

       getSupportFragmentManager().beginTransaction().
            replace(R.id.fragmentContainer, new MyListFragment()).commit();


}
}

you fragment should look like this

public class MyListFragment extends Fragment implements
    android.widget.CompoundButton.OnCheckedChangeListener {

ListView lv;
ArrayList<Planet> planetList;
PlanetAdapter plAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_view, container, false);
}


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

     lv = (ListView) findViewById(R.id.listview);
    displayPlanetList();
}


private void displayPlanetList() {

    planetList = new ArrayList<Planet>();
    planetList.add(new Planet("Margherita", 6, "€"));
    planetList.add(new Planet("Diavola", 7,"€"));
    planetList.add(new Planet("Bufalina", 5,"€"));
    planetList.add(new Planet("Marinara", 5,"€"));
    planetList.add(new Planet("Viennese", 4,"€"));

    plAdapter = new PlanetAdapter(planetList, this);
    lv.setAdapter(plAdapter);
}


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

    int pos = lv.getPositionForView(buttonView);
    if (pos != ListView.INVALID_POSITION) {
        Planet p = planetList.get(pos);
        p.setSelected(isChecked);


        /*Toast.makeText(
                this,
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*/
    }

}
public void showResult(View v) {
    String result = "Selected Product are :";
    int totalAmount=0;

    for (Planet p : plAdapter.getBox()) {
        if (p.selected){
            result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
            //if (p.quantità.equals("") && p.quantità.equals(null) ){
            System.out.println("leggo questo record:"+p.name + " " + p.distance + " " + p.quantità );

            System.out.println("leggo questo p.getquatità :"+p.quantità );
            //}
            //else{
                System.out.println("leggo questo in p.quantità: "+p.getQuantità());
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                totalAmount+=p.distance * quantitaInt;
            //}
        }
    }
//      Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
    //Integer.toString(totalAmount);
    Intent i = new Intent(getActivity(), SecondActivity.class);
    i.putExtra("NomeDati1", result);
    i.putExtra("NomeDati2", String.valueOf(totalAmount));
    startActivity(i);

}
}

you adapter class remains as is.

MobDev
  • 464
  • 4
  • 14
0

This is your Activity class converted into fragment

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ListView;

public class Main extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener {

    private ListView lv;
    private ArrayList<Planet> planetList;
    private PlanetAdapter plAdapter;

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

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

        displayPlanetList();

        return rootView;

    }

    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", 6, "€"));
        planetList.add(new Planet("Diavola", 7, "€"));
        planetList.add(new Planet("Bufalina", 5, "€"));
        planetList.add(new Planet("Marinara", 5, "€"));
        planetList.add(new Planet("Viennese", 4, "€"));

        plAdapter = new PlanetAdapter(planetList, getActivity());
        lv.setAdapter(plAdapter);
    }

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

        int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);

            /*
             * Toast.makeText( this, "Clicked on Planet: " + p.getName() +
             * ". State: is " + isChecked, Toast.LENGTH_SHORT).show();
             */
        }

    }

    public void showResult(View v) {
        String result = "Selected Product are :";
        int totalAmount = 0;

        for (Planet p : plAdapter.getBox()) {
            if (p.selected) {
                result += "\n" + p.name + " " + p.distance + "€" + "q.tà :" + p.getQuantità();
                // if (p.quantità.equals("") && p.quantità.equals(null) ){
                System.out.println("leggo questo record:" + p.name + " " + p.distance + " " + p.quantità);

                System.out.println("leggo questo p.getquatità :" + p.quantità);
                // }
                // else{
                System.out.println("leggo questo in p.quantità: " + p.getQuantità());
                int quantitaInt = Integer.parseInt(p.getQuantità());
                totalAmount += p.distance * quantitaInt;
                // }
            }
        }
        // Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount,
        // Toast.LENGTH_LONG).show();
        // Integer.toString(totalAmount);
        Intent i = new Intent(getActivity(), SecondActivity.class);
        i.putExtra("NomeDati1", result);
        i.putExtra("NomeDati2", String.valueOf(totalAmount));
        startActivity(i);

    }
}
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154