gpt4 book ai didi

android - myView.setLayoutParams(otherView.getLayoutParams());不工作,为什么?

转载 作者:行者123 更新时间:2023-11-30 04:11:44 25 4
gpt4 key购买 nike

在 xml 中获取我的 TextView:

<TextView  
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="left"
android:text="TextView"/>

我想创建多个 TextView,但我希望它们看起来与this 相同。

所以我尝试了:

TextView newTextView = new TextView(this);

newTextView.setLayoutParams(myTextView.getLayoutParams());

我认为这应该从 xml 直接(?)获取 myTextView 的所有布局参数,并将它们传递给 newTextView 以进行设置。

我的问题是:没有任何反应。没有生效,为什么?

最佳答案

这是一个示例项目,表明它可以正常工作。您可以通过查看可视化编辑器的预览看到它的工作原理,它看起来与运行时显示的不同。我认为你的错误是你没有为加权 View 设置 0px(或 0dp,零仍然是零)。

main.xml(布局):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/container">

<TextView android:id="@+id/textView1" android:layout_width="wrap_content"
android:layout_height="0px" android:text="TextView1"
android:layout_weight="1" android:background="#ffff0000" />

<TextView android:id="@+id/textView2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="TextView2"
android:background="#ff00ff00" />

</LinearLayout>

测试 Activity .java :

public class TestActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv1=(TextView)findViewById(R.id.textView1);
final TextView tv2=(TextView)findViewById(R.id.textView2);
final LayoutParams layoutParams=tv1.getLayoutParams();
tv2.setLayoutParams(layoutParams);
// adding textView programatically:
final TextView tv3=new TextView(this);
tv3.setText("textView3");
tv3.setBackgroundColor(0xff0000ff);
tv3.setLayoutParams(layoutParams);
final ViewGroup root=(ViewGroup)findViewById(R.id.container);
root.addView(tv3);
}
}

关于android - myView.setLayoutParams(otherView.getLayoutParams());不工作,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10762220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com