【发布时间】:2014-02-03 09:02:05
【问题描述】:
我只是使用 LayoutInflater 从除 activity_main.xml 之外的 layout.xml 文件中获取视图(按钮)。但是当我更改按钮的 setText("") 属性时,按钮属性不会更新。
我正在检查是否可以更改 testlayout.xml 中按钮元素的文本属性但是当我在 onCreate 中设置 Button 的属性并且当我检查调用中未更改的属性时...
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.testlayout, null);
Button btn = (Button)linearLayout.findViewById(R.id.testbtn);
btn.setText("Hello");
}
public void call(View v){
Button btn = (Button)findViewById(R.id.testBtn);
Toast.makeText(this, btn.getText(), Toast.LENGTH_SHORT).show();
}
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/mainBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="73dp"
android:text="Button"
android:onClick="call"
/>
</RelativeLayout>
testlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/testBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
【问题讨论】:
-
你在哪里将错误的布局添加到活动中?
-
我正在检查是否可以更改 testlayout.xml 中按钮元素的文本属性但是当我在 onCreate 中设置按钮的属性以及在调用中检查该属性时不是变了……
-
但除非您将其添加到活动中,否则您不会看到按钮文本发生变化
-
在调用(查看 v)函数中我正在检查更改属性..
-
跟随 vipul; 的回答并尝试
标签: java android xml android-layout