-1

Hello im new in Android studio and tried to make a button working in a fragment but it doesnt work?

My Fragment code:

package layout;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SearchViewCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;   
import com.marcphi.csgoskin.R;
import com.marcphi.csgoskin.SkinListActivity;

public class NewsFragment extends Fragment implements View.OnClickListener {

    View view;
    Button btn;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_news, container, false);  
        btn = (Button) view.findViewById(R.id.button1);
        btn.setOnClickListener(this);         
        return  view;
    }
    public void onClick(View view){
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
        Intent intent = new Intent(getActivity(), SkinListActivity.class);
        startActivity(intent);  
    }       
}

There is now Error on debugging .

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Marc
  • 3
  • 2

3 Answers3

0

One way to do this:

btn = (Button) view.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on click   

                Snackbar.make(v, 
                              "Replace with your own action", 
                               Snackbar.LENGTH_LONG)
                         .setAction("Action", null).show();

                Intent intent = new Intent(getActivity(),
                                           SkinListActivity.class);
                startActivity(intent);  
            }
        });
Julius
  • 159
  • 1
  • 1
  • 13
0

In your onClick method add:

If (view.getId() == R.id.button1) {
   // Here place code of onClick method
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Polurival
  • 58
  • 1
  • 9
0

It doesnt work because Snackbar.make() takes coordinatorLayout as first argument and you are passing button in it.

If you want to use Snackbar you must use CoordinatorLayout as your rootView in your fragment and then pass it to Snackbar like this:

Snackbar.make(coordinatorLayout, "Replace with your own action", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();
Jozef Dochan
  • 926
  • 10
  • 27