Android Programmatically setting button text

后端 未结 4 873
小蘑菇
小蘑菇 2020-12-30 06:42

Does anybody know how to programmatically set the text of a button?

thing is i\'m not calling this from the main layout(setContentView) i\'m calling it in a view tha

相关标签:
4条回答
  • 2020-12-30 06:51

    check R.java files import statement

    are you sure that you have import it of the project you use .. and just format your layout (.xml ) file save it and again type the same statement

    0 讨论(0)
  • 2020-12-30 07:11

    your mButton is null.so NPE.are you refrenced xml resources after setContentView

    onCreate(){
    ...
    setContentView(R.layout.yourlayout);
    
    Button mButton=(Button)findViewById(R.id.contact);
    mButton.setText("number");
    
    }
    
    0 讨论(0)
  • 2020-12-30 07:13

    Then use your view's object to initialize it:

    Button mButton = (Button)your_view_object.findViewById(R.id.contact);
    mButton.setText("number");
    

    When you try to identify a view other than your Activity's layout, you have to pass the reference of that view like this. If not Android will keep looking for this element from the layout which you provided in the setContentView().

    For example, consider you have inflated a view like this:

    View View = mInflater.inflate(R.layout.gridelement, null);
    

    Then use this View's object for the Button present in that inflated layout:

      Button mButton = (Button)View.findViewById(R.id.contact);
    
    0 讨论(0)
  • 2020-12-30 07:15

    change your code as:

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);//set layout here in which u have add contact in xml
            Button mButton=(Button)findViewById(R.id.contact);
            mButton.setText("number");
    

    EDIT: Your \res\layout\main.xml look like as:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    <Button
           android:id="@+id/contact"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_below="@+id/address"
           android:layout_toLeftOf="@+id/badge"
           android:background="@drawable/ic_btn_call"
           android:textSize="10dp"
           android:textStyle="bold"
           android:textColor="@color/white"/>
    </LinearLayout>
    
    0 讨论(0)
提交回复
热议问题