Guga Rai
Guga Rai

Reputation: 49

I Cannot Change Background Color of Fragment in Android

I want to change the background color of a fragment. But when I click on the button nothing happens.

In my main activity layout XML file I imported the fragment.

Here is my code:

public class Top_Fragment extends Fragment implements View.OnClickListener {
    Button button;
    LinearLayout mLinearLayout;

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        button = (Button) getActivity().findViewById(R.id.button);
        mLinearLayout = (LinearLayout) getActivity().findViewById(R.id.layout);
    }

    @Override
    public void onClick(View v) {
        mLinearLayout.setBackgroundColor(Color.parseColor("#ffffbb33"));
    }
}

Upvotes: 0

Views: 3262

Answers (2)

jayendrasinh vaghela
jayendrasinh vaghela

Reputation: 29

Your code is perfectly but you need to add button.setOnClickListener(this);

     @Override
     public void onActivityCreated(Bundle savedInstanceState) {
     super.onActivityCreated(savedInstanceState);

     button = (Button)getActivity().findViewById(R.id.button);
     mLinearLayout = (LinearLayout)getActivity().findViewById(R.id.layout);
     button.setOnClickListener(this); }

Upvotes: 1

Joe Maher
Joe Maher

Reputation: 5460

Replace

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

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    button = (Button)getActivity().findViewById(R.id.button);
    mLinearLayout = (LinearLayout)getActivity().findViewById(R.id.layout);
}

with

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

    View fragmentView = inflater.inflate(R.layout.top_fragment,container, false)

    button = (Button)fragmentView.findViewById(R.id.button);
    button.setOnClickListener(this);
    mLinearLayout = (LinearLayout)fragmentView.findViewById(R.id.layout);

    return fragmentView;

}

Upvotes: 0

Related Questions