如何使用按钮实现切换按钮

时间:2016-06-02 15:17:18

标签: android

Helllo,我是编程android的新手,我的问题是有一个方法让按钮创建一个新的开关按钮,带有一些我希望的caratteristic,例如名称和数字。

1 个答案:

答案 0 :(得分:2)

它不是那么清楚你想要什么 但我做了一个有按钮的应用程序 单击按钮时,它会向视图添加一个开关 (但我不明白你的姓名和号码)

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //adding the switch button
            Switch addedSwitch = new Switch(getBaseContext());
            LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            linearLayout.addView(addedSwitch, layoutParams);
        }});
}}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.recntrek7.stack.MainActivity">
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="press"
    android:id="@+id/button"
    android:layout_marginTop="62dp" /></LinearLayout>