我想以编程方式生成一个布局,并在布局中生成一个textview和edittext。我怎么能让它看起来像这样?
有代码,但它没有用:(
RelativeLayout mRlayout = (RelativeLayout) findViewById(R.id.mRlayout);
RelativeLayout.LayoutParams mRparams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
EditText myEditText = new EditText(context);
myEditText.setLayoutParams(mRparams);
mRlayout.addView(myEditText);
答案 0 :(得分:1)
首先在xml文件中添加线性布局,如
<LinearLayout
android:id="@+id/horizantalLinear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horiontal" >
</LinearLayout>
然后在java代码中创建线性布局对象
EditText myEditText = new EditText(this); // Pass it an Activity or Context
LayoutParams editLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
myEditText.setLayoutParams(editLayoutParams);
myEditText.setVerticalFadingEdgeEnabled(true);
myEditText.setHint(hint);
myEditText.setId(Integer.parseInt(id));
myLayout.addView(myEditText);// myLayout is object of linear layout created in xml file
答案 1 :(得分:0)
请尝试这种方式,希望这有助于您解决问题。
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
TextView textView = new TextView(this);
textView.setText("TextView");
layout.addView(textView);
EditText editText = new EditText(this);
editText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1f));
editText.setHint("EditText");
layout.addView(editText);
setContentView(layout);
}
}
答案 2 :(得分:0)
我建议在layout.xml中定义LinearLayout,在Java中定义Create对象,然后在LinearLayout中添加textview。
<LinearLayout
android:id="@+id/relatedChannels"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
爪哇
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout cat_linear=(LinearLayout) findViewById(R.id.list_Category);
TextView tv = new TextView(context);
tv.setText("This is Text View");
tv.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
cat_linear.addView(tv);
EditText ed = new EditText (context);
ed.setHint("EditText");
ed.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
cat_linear.addView(ed);
}