gosulove gosulove - 4 months ago 47
Android Question

OnClickListener not working on Fragment

I trying out Fragment and have a problem with OnClickListener. Anyone can help?

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_one frag1=new frag_one();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.top,frag1,"");
transaction.commit();
}
}


frag_one.java

public class frag_one extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_frag_one,container,false);
}

public class calculator extends AppCompatActivity implements View.OnClickListener {
TextView get_result;
EditText get_num1;
EditText get_num2;
Button get_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_one);
get_result=(TextView)findViewById(R.id.result);
get_num1=(EditText) findViewById(R.id.num1);
get_num2=(EditText) findViewById(R.id.num2);
get_button=(Button)findViewById(R.id.submit);
get_button.setOnClickListener(this);
}
public void onClick(View v) {
int num1=Integer.parseInt((get_num1.getText().toString()));
int num2=Integer.parseInt((get_num2.getText().toString()));
int sum=num1+num2;
get_result.setText(Integer.toString(sum));
}
}
}


When I run on normal activity without using Fragment. When i click the button, the calculation works. But when i move to Fragment, its not working. Please help! thx

enter image description here

Answer

You made a second Activity that uses the layout of the Fragment instead of actually placing the logic into the Fragment class....

public class frag_one extends Fragment implements View.OnClickListener {

    TextView get_result;
    EditText get_num1;
    EditText get_num2;
    Button get_button;

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

        get_result=(TextView)rootView.findViewById(R.id.result);
        get_num1=(EditText)rootView.findViewById(R.id.num1);
        get_num2=(EditText) rootView.findViewById(R.id.num2);
        get_button=(Button)rootView.findViewById(R.id.submit);
        get_button.setOnClickListener(this);

        return rootView;
    }

    public void onClick(View v) {
        // TODO: Check v.getId() == R.id.submit
        int num1=Integer.parseInt((get_num1.getText().toString()));
        int num2=Integer.parseInt((get_num2.getText().toString()));
        int sum=num1+num2;
        get_result.setText(Integer.toString(sum));
    }
}
Comments