我遵循以下代码,将textCheckedView添加到相对布局中:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
final RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
final RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.ALIGN_PARENT_TOP);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
int ids=0;
public void onClick(View v) {
String test ="test";
ids++;
final AlarmCheckedTextView checkedTV = createButton(test,ids);
checkedTV.setVisibility(1);
p.addRule(RelativeLayout.BELOW,checkedTV.getId());
rlayout.addView(checkedTV,p);
}
});
}
private CustomCheckedTextView createButton(String text, int id)
{
final CustomCheckedTextView checkedTV = new CustomCheckedTextView(this,text);
checkedTV.setId(id);
return checkedTV;
}
}
但是,点击CustomCheckedTextView
后,我在RelativeLayout
添加Button
时遇到问题。我的意思是一切都成功添加,但都在一个地方。如何以编程方式添加以下元素?
答案 0 :(得分:1)
你可以这样理解:---
假设您要创建两个TextView&想把一个textview放在另一个下面: -
RelativeLayout relative = new RelativeLayout(this);
TextView proposalA = new TextView(this);
proposalA.setText("Proposal A:-");
proposalA.setTextColor(Color.BLACK);
proposalA.setId(R.id.propasal_a);//set id for this TextView you can put unique id for every content in your string folder otherwise you can set id like this: tv1.setId((int)System.currentTimeMillis());
proposalA.setTextSize(16);
proposalA.setTypeface(Typeface.DEFAULT_BOLD);
RelativeLayout.LayoutParams relative_params_a = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
relative_params_a.setMargins(20, 6, 0, 0);
proposalA.setLayoutParams(relative_params_a); relative .addView(proposalA); //在主要相对布局中添加textview 现在你想把(textview)proposalB放在textview(ProposalA)下面,然后: - 对于第一个TextView下的第二个TextView,使用 addRule 像这样:---
TextView proposalB = new TextView(this);
proposalB.setText("Proposal B:-");
proposalB.setTextColor(Color.BLACK);
proposalB.setId(R.id.propasal_b);
proposalB.setTextSize(16);
proposalB.setTypeface(Typeface.DEFAULT_BOLD);
RelativeLayout.LayoutParams relative_params_b = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
relative_params_b.addRule(RelativeLayout.BELOW,proposalA.getId());
relative_params.setMargins(20, 6, 0, 0);
proposalB.setLayoutParams(relative_params_b);
relative .addView(proposalB);