Marco Panarelli
Marco Panarelli

Reputation: 35

Use button in fragments

I have to increment/decrement a text in a Textview with two button (one increment,one decrement). I am doing all in a Fragment and I noticed that is a little bit different work in them.

These are buttons and textview

<Button
        android:layout_width="36dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="90dp"
        android:text="-"
        android:id="@+id/minus"
        android:onClick="decrement"
        />
        <TextView
        android:layout_width="36dp"
        android:layout_height="match_parent"
        android:paddingTop="15dp"
        android:textSize="18sp"
        android:id="@+id/text"
        android:textAlignment="center"
        android:texr="stats"/>
         <Button
        android:layout_width="36dp"
        android:layout_height="match_parent"
        android:text="+"
        android:id="@+id/plus"
        android:onClick="increment"
        />

This is the Fragment's code

public class MyFragment extends Fragment {
int stat= 0;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_my_fragment, container, false);
}
public void increment(View view){
    stat= stat+ 1;
    displaytext();
}

public void decrement(View view){
        stat = stat - 1;
        displaytext();
}

public void displaytext(){
    TextView textViewevstat = (TextView) getView().findViewById(R.id.text);
    textViewevstat.setText("" + stat);
}
}

It don't take me syntax errors or similar but ,in the emulator ,the app crash when i press one button. I have to remake all this passage other times but ,in this case, i think is sufficient to change ids and method's name.

Upvotes: 0

Views: 381

Answers (1)

Dhruv Kaushal
Dhruv Kaushal

Reputation: 680

Here do this

View v;         // Declare this 

public class MyFragment extends Fragment {
int stat= 0;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

     v=inflater.inflate(R.layout.fragment_my_fragment, container, false);
     return v;
}
public void increment(View view){
    stat= stat+ 1;
    displaytext();
}

public void decrement(View view){
        stat = stat - 1;
        displaytext();
}

public void displaytext(){
    TextView textViewevstat = (TextView)v.findViewById(R.id.text);// use it here
    textViewevstat.setText("" + stat);
}

}

Upvotes: 1

Related Questions