एंड्रॉइड में गतिशील रूप से एक बटन कैसे जोड़ें?


119

एंड्रॉइड में गतिशील रूप से एक बटन कैसे जोड़ें?

जवाबों:


128
Button myButton = new Button(this);
myButton.setText("Push Me");

LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);

इस उदाहरण पर एक नजर डालें


1
मैंने URL अपडेट किया क्योंकि पुराने वाले ने 404 दिया था। कृपया जांच लें कि मैंने सही पृष्ठ का संदर्भ दिया है।
छिपकली

1
क्या आप पूरी तरह से योग्यता प्राप्त कर सकते हैं LayoutParams? मैं इस नाम के साथ 12 से अधिक कक्षाएं देखता हूं।
सईद नेमाटी

1
@Saeed इस विशिष्ट उदाहरण में यह LinearLayout से संबंधित लेआउटपार्म्स है। android.widget.LinearLayout.LayoutParams
बैसड्रॉप कंबरवॉबबॉव

54

इसे इस्तेमाल करे:

for (int i = 1; i <= 20; i++) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    Button btn = new Button(this);
    btn.setId(i);
    final int id_ = btn.getId();
    btn.setText("button " + id_);
    btn.setBackgroundColor(Color.rgb(70, 80, 90));
    linear.addView(btn, params);
    btn1 = ((Button) findViewById(id_));
    btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(view.getContext(),
                    "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

1
बटन क्यों जोड़ा गया है, तो क्लिक श्रोता को सेट करने से पहले प्राप्त करें। क्या आप श्रोता को नहीं जोड़ सकते थे, फिर इसे लेआउट में जोड़ सकते हैं और किया जा सकता है?
rwilson04

सबसे अच्छा जवाब क्योंकि आप एक आईडी सेट करके बटनों पर क्लिक कर सकते हैं :)
boctulus

10

इसे इस्तेमाल करे:

LinearLayout ll = (LinearLayout)findViewById(R.id.layout);

Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);

यहाँ पर R.id.layout का क्या जिक्र है? मैं अप्रचलित के रूप में लेआउट प्राप्त करता रहता हूं
अन्ना गोल्डबर्ग

आपकी प्रासंगिक xml फ़ाइल में @AnnaGoldberg आपके पास एक LinearLayout परिभाषित होना चाहिए। इस अंश में उन्होंने अपना LinearLayout एक लेआउट नामक आईडी दिया, जैसे: android:id="@+id/layout"अपनी LinearLayout xml परिभाषा में।
Amyga17

6

इसे इस्तेमाल करे

private void createLayoutDynamically(int n) {

    for (int i = 0; i < n; i++) {
        Button myButton = new Button(this);
        myButton.setText("Button :"+i);
        myButton.setId(i);
        final int id_ = myButton.getId();

        LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
        layout.addView(myButton);

        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(DynamicLayout.this,
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

6
for (int k = 1; k < 100; k++) {
    TableRow row = new TableRow(this);

    innerloop:
    for (int l = 1; l < 4; l++) {
        btn = new Button(this);
        TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layout.setWeightSum(12.0f);
        tr.weight = 0;
        btn.setLayoutParams(tr); 
        btn.setTextColor(a);
        btn.setHeight(150);

        btn.setWidth(150);
        btn.setId(idb);
        btn.setText("Button " + idb);
        row.addView(btn);
    }
}

5

इस कोड को आज़माएं

 Button btn=new Button(this);
btn.setId(btn);
btn.setBackgroundResource(R.drawable.image);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
Relativelayout.addView(btn); 

4

इस कोड को आज़माएं। यह ठीक काम करेगा ..

public class DynamicViewsActivity extends Activity {

Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_dynamic_views);
    ScrollView scrl=new ScrollView(this);
    final LinearLayout ll=new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(100, 500, 100, 200);
    scrl.addView(ll);
    Button add_btn=new Button(this);
    add_btn.setText("Click Here");

    ll.addView(add_btn, layoutParams);


    final Context context = this;

    add_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(context, App2Activity.class);
            startActivity(intent);
        }
    });
    this.setContentView(scrl);
}
}

4

इसे चेक करें।

LinearLayout ll_Main  = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());

ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);

final Button button01    = new Button(getActivity());
final Button button02    = new Button(getActivity());   
final Button button03    = new Button(getActivity());
final Button button04    = new Button(getActivity());

ll_Row01.addView(button01);
ll_Row01.addView(button02);

ll_Row02.addView(button03);
ll_Row02.addView(button04);

ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);

button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);

3

निम्नलिखित कोड का प्रयास करें।

LinearLayout layout = (LinearLayout) findViewById(R.id.llayout); 
layout.setOrientation(LinearLayout.VERTICAL);

Button btn = new Button(this);
btn.setText("Button1");

layout.add(btn);

btn = new Button(this);
btn.setText(Button2);
layout.add(btn);

इस तरह आप अपनी आवश्यकताओं के अनुसार बटन जोड़ते हैं।


3
public void add_btn() {

    lin_btn.setWeightSum(3f);
    for (int j = 0; j < 3; j++) {
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params1.setMargins(10, 0, 0, 10);
        params1.weight = 1.0f;

        LinearLayout ll;
        ll = new LinearLayout(this);
        ll.setGravity(Gravity.CENTER_VERTICAL);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setLayoutParams(params1);

        final Button btn;
        btn = new Button(DynamicActivity.this);

        btn.setText("A"+(j+1));
        btn.setTextSize(15);
        btn.setId(j);
        btn.setPadding(10, 8, 10, 10);

        ll.addView(btn);

        lin_btn.addView(ll);


        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if(v.getId()==0)
                {
                    txt_text.setText("Hii");
                }else if(v.getId()==1)
                {
                    txt_text.setText("hello");
                }else if(v.getId()==2)
                {
                    txt_text.setText("how r u");
                }



            }
        });
    }

}

2

वास्तव में मैं xml लेआउट फ़ाइल में कुछ भी जोड़ता हूं जिसका उपयोग किया जा सकता है! फिर विशिष्ट गतिविधि के स्रोत कोड से मुझे ऑब्जेक्ट को इसकी आईडी से मिलता है और मैं दृश्यता विधि के साथ "प्ले" करता हूं।

यहाँ एक उदाहरण है:

((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);


1
यह वह नहीं है जो पूछा जा रहा है। जब लोग गतिशील रूप से जोड़ने के बारे में पूछते हैं तो उनका मतलब बिना लेआउट के होता है। आप जो कर रहे हैं वह अनहाइडिंग है ... जोड़ना नहीं।
मोग

2

मैंने एक LinearLayout में कई TextViews जोड़ने के लिए इस (या बहुत समान) कोड का उपयोग किया है:

// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;

// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.FILL_PARENT);

// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);

TextView tv;

for (int i = 0; i < namesLength; i++) {
    // Grab the name for this "button"
    final String name = names[i];

    tv = new TextView(context);
    tv.setText(name);

    // TextViews CAN have OnClickListeners
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            label.setText("Clicked button for " + name); 
        }
    });

    nameButtons.addView(tv, params);
}

इसके और डिक्लाव 795 के कोड के बीच मुख्य अंतर यह सेट नहीं है () और फिर से मिलता है () प्रत्येक टेक्स्ट व्यू के लिए आईडी - मुझे यह अनावश्यक लगा, हालांकि मुझे बाद में एक सामान्य हैंडलर रूटीन में प्रत्येक बटन की पहचान करने की आवश्यकता हो सकती है ( उदाहरण के लिए, प्रत्येक पाठ दृश्य के लिए onClick () द्वारा बुलाया गया।


2
Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);

1
Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");


LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
 myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(DynamicLayout.this,
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });

1

यदि आप डायनामिक बटन जोड़ना चाहते हैं तो यह कोशिश करें:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    for (int i = 1; i <= 5; i++) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
        layout.setOrientation(LinearLayout.VERTICAL);
        Button btn = new Button(this);
        btn.setText("    ");
        layout.addView(btn);
    }

}

0

आप अपने बटन के लिए एक आधार लेआउट बना सकते हैं और गतिशील रूप से केवल वही बदल सकते हैं जो विशिष्ट है, इस परियोजना की तरह मैं एक मटीरियल डिज़ाइन कोर्स से विभिन्न अभ्यास चलाने के लिए बना हूं जो मैं ले रहा हूं:

इस उदाहरण में, मैं एक पूर्वनिर्मित AppCompatButton का उपयोग करता हूं:

layout_base_button.xml

<android.support.v7.widget.AppCompatButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/btn_base"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="8dp"
    style="@style/RaisedButton"
    >

</android.support.v7.widget.AppCompatButton>


<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textSize">11sp</item>
    <item name="android:textStyle">bold</item>
</style>

और MainActivityमैंने कुछ उदाहरणों को बनाया और जो मुझे चाहिए था उसे बदल दिया, जैसे बटन टेक्स्ट और ऑनक्लिक इवेंट:

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="udemy.android.materialdesign.MainActivity">

    <LinearLayout
        android:id="@+id/base_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

    </LinearLayout>


</ScrollView>



public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout baseLayout = findViewById(R.id.base_layout);

        baseLayout.addView(createButton("TextFields", baseLayout,
                view -> startActivity(createIntent(TextFieldsActivity.class))
        ));

        baseLayout.addView(createButton("Buttons", baseLayout,
                view -> startActivity(createIntent(ButtonsActivity.class))
        ));

        baseLayout.addView(createButton("Toolbar", baseLayout,
                view -> startActivity(createIntent(ToolbarActivity.class))
        ));

    }

    private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
        View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
        AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);

        btnBase.setText(text);
        btnBase.setOnClickListener(onClickEvent);
        return btnBase;
    }

    private Intent createIntent(Class<?> cls) {
        return new Intent(this, cls);
    }
}

देर से आने के लिए क्षमा करें...


-4

में mainactivity.xmlलिखने:

<Button
    android:id="@+id/search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search" 
    android:visibility="invisible"/>

में main.javaलिखने:

Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.