Android以编程方式设置按钮文本 [英] Android Programmatically setting button text

查看:238
本文介绍了Android以编程方式设置按钮文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何以编程方式设置按钮的文本吗?

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

我不是从主布局(setContentView)调用它,而是在asynctask后膨胀的视图中调用它 这是我尝试过的方法,但这在第二行给出了空指针异常

thing is i'm not calling this from the main layout(setContentView) i'm calling it in a view thats inflated after an asynctask heres what i have tried but this is giving a null pointer exception on the 2nd line

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

这是我调用按钮的布局

   <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"/>

在这里,我的观点正在膨胀

here my view i'm inflating

ClubInfo = LayoutInflater.from(getBaseContext()).inflate(R.layout.clubinfocell,
                null);

        TextView TeamNameText = (TextView) ClubInfo.findViewById(R.id.TeamName);
        TeamNameText.setText(teamName);

        TextView AddressText = (TextView) ClubInfo.findViewById(R.id.address);
        AddressText.setText(address1);



        Button mButton=(Button)ClubInfo.findViewById(R.id.contact);
        mButton.setText(telephone);

推荐答案

然后使用视图的对象对其进行初始化:

Then use your view's object to initialize it:

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

当您尝试识别活动"布局以外的视图时,必须像这样传递该视图的引用.如果不是这样,Android将继续从您在setContentView()中提供的布局中查找此元素.

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);

然后将此视图的对象用于该膨胀布局中存在的Button:

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

  Button mButton = (Button)View.findViewById(R.id.contact);

这篇关于Android以编程方式设置按钮文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆