我想以编程方式在android中添加按钮,按钮的xml文件将是
<Button
android:textStyle="bold"
android:background="@drawable/blue"
android:textColor="@drawable/blue_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/funny_excuses"
android:id="@+id/funny"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:textSize="25sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
最好的方法是什么? 我只会更改每个新按钮的文本.. 也许我会有另一种按钮类型,比如其他背景和文字颜色..
答案 0 :(得分:1)
幻灯 - &GT; RES - &GT;值 - &GT; style.xml
<style name="othername" >
<item name="android:layout_width">match_parent</item>
<item name="android:textColor">#000000</item>
<item name="android:textSize">20sp</item>
<item name="android:gravity">left</item>
<item name="android:layout_marginLeft">30sp</item>
<item name="android:layout_marginRight">30sp</item>
<item name="android:layout_marginTop">10sp</item>
</style>
<Button
style="@style/othername"
/>
答案 1 :(得分:1)
确定要做一件事。只需要更改按钮text.so,以编程方式为按钮对象保留setText()和setBackground()......
答案 2 :(得分:1)
还可以从代码创建此Button xml并扩展布局资源: button.xml:
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:textStyle="bold"
android:background="@drawable/blue"
android:textColor="@drawable/blue_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/funny_excuses"
android:id="@+id/funny"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:textSize="25sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
代码:
Button button = (Button) getLayoutInflater().inflate(R.layout.button, null);
button.setText("Hello world");
RelativeLayout ll = (RelativeLayout) findViewById(R.id.ll); //layout to add
ll.addView(button);
答案 3 :(得分:1)
在您的布局中创建按钮,然后使用yourButton.setVisibility(View.GONE);
隐藏它,并使用yourButton.setVisibility(View.VISIBLE);
使其可见。
答案 4 :(得分:1)
layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
.javafile
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//Find you parent layout which we'll be adding your button to:
LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.addView(createdButton);
//if no rooms make tvnorooms disappear
break;
}