Reputation: 49
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
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
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