如何在代码而不是 XML 文件中更改 Android Button 小部件的文本?
7 回答
我能够像这样更改按钮的文本:
import android.widget.RemoteViews;
//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
这很容易
Button btn = (Button) findViewById(R.id.btn);
btn.setText("MyText");
我的 layout.xml 中有一个按钮,它被定义为视图,如下所示:
final View myButton = findViewById(R.id.button1);
在将其定义为按钮之前,我无法更改其上的文本:
final View vButton = findViewById(R.id.button1);
final Button bButton = (Button) findViewById(R.id.button1);
当我需要更改文本时,我使用了bButton.setText("Some Text");
,当我想要更改视图时,我使用了vButton.
工作得很好!
使用 java 进行交换。setText = "...",对于 java 类还有更多的实现方法。
//button fechar
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
View.OnClickListener close = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnclose.isClickable()) {
btnOpen.setEnabled(true);
btnOpen.setText("ABRIR");
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
} else {
btnOpen.setEnabled(false);
btnOpen.setText("ABERTO");
btnclose.setEnabled(true);
btnclose.setText("FECHAR");
}
Toast.makeText(getActivity(), "FECHADO", Toast.LENGTH_SHORT).show();
}
};
btnclose.setOnClickListener(close);
这可能是题外话,但对于那些正在努力如何准确更改按钮文本字体的人(这是我的情况,Skatephone 的回答对我有帮助)我是这样做的(如果你制作了按钮 ind 设计模式):
首先,我们需要将按钮的字符串名称“转换”(这是一种错误的解释方式,但直截了当)从 xml 转换为 java,因此我们将上述代码粘贴到 MainActivity.java
重要的!将代码放在 OnCreate 方法下!
import android.widget.RemoteViews;
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
记住:
my_layout
必须用按钮所在的 xml 文件替换
Counter
必须用您的按钮的 id 名称替换 ( "@+id/ButtonName"
)
如果要更改按钮文本,只需插入文本代替"Set button text here"
这是您更改字体的部分:
现在您已从 xml“转换”为 java,您可以为 TextView 设置一个 Typeface 方法。将以下代码完全粘贴在上面刚刚描述的上一个代码下
TextView txt = (TextView) findViewById(R.id.text_your_text_view_id);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MyFontName.ttf");
txt.setTypeface(font);
代替text_your_text_view_id
您放置按钮的 id 名称(如之前的代码)并代替MyFontName.ttf
您放置所需的字体
警告!这假设您已经将所需的字体放入 assets/font 文件夹中。例如资产/字体/MyFontName.ttf
//文字按钮:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" text button" />
// 彩色文本按钮:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text button"
android:textColor="@android:color/color text"/>
// 背景按钮
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text button"
android:textColor="@android:color/white"
android:background="@android:color/ background button"/>
// 文字大小按钮
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text button"
android:textColor="@android:color/white"
android:background="@android:color/black"
android:textSize="text size"/>