Reputation: 8408
I'm trying to change the colour of my text views within a RelativeLayout
, but for some reason it's not working.
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.TextViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.companyname.projectname.R;
import static com.companyname.projectname.R.id.FL_relativeLayout;
public class FragmentFL extends android.support.v4.app.Fragment {
public FragmentFL() {
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fl, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
RelativeLayout relativelayout = v.findViewById(FL_relativeLayout);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView txt1 = new TextView(getActivity());
txt1.setText("Hello world");
TextViewCompat.setTextAppearance(txt1, android.R.style.TextAppearance_Large);
txt1.setTextColor(Color.BLACK);
TextView txt2 = new TextView(getActivity());
txt2.setText("Bonjour le monde");
TextViewCompat.setTextAppearance(txt2, android.R.style.TextAppearance_Medium);
txt1.setTextColor(Color.BLACK);
rlp.setMargins(0, 0, 0, 20);
rlp.addRule(RelativeLayout.BELOW, txt1.getId());
txt1.setLayoutParams(rlp);
txt2.setLayoutParams(rlp);
relativelayout.addView(txt1);
relativelayout.addView(txt2);
// set IDs for text views
txt1.setId(View.generateViewId());
txt2.setId(View.generateViewId());
super.onActivityCreated(savedInstanceState);
}
}
Upvotes: 0
Views: 855
Reputation: 13627
Alignment is not good because you have to set Id for the view before setting rule.
Code:
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView txt1 = new TextView(this);
txt1.setText("Hello world");
txt1.setTextColor(Color.BLACK);
TextViewCompat.setTextAppearance(txt1, android.R.style.TextAppearance_Large);
TextView txt2 = new TextView(this);
txt2.setText("Bonjour le monde");
txt2.setTextColor(Color.BLACK);
TextViewCompat.setTextAppearance(txt2, android.R.style.TextAppearance_Medium);
txt1.setId(View.generateViewId());
txt2.setId(View.generateViewId());
rlp.setMargins(0, 0, 0, 20);
rlp.addRule(RelativeLayout.BELOW, txt1.getId());
txt2.setLayoutParams(rlp);
relativelayout.addView(txt1);
relativelayout.addView(txt2);
Upvotes: 1
Reputation: 1162
Set appearance befor set text color. The Appearance overrides the textcolor And Generate id befor set rule.
Upvotes: 2