Получил мой TextView в xml:
<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"/>
Я хочу создать несколько TextViews, но я хочу выглядеть так же, как это.
Поэтому я попробовал:
TextView newTextView = new TextView(this);
newTextView.setLayoutParams(myTextView.getLayoutParams());
Я думаю, что это должно получить все параметры макета из myTextView straigthlghly (?) Из xml и передать их в newTextView для их установки.
Моя проблема: ничего не происходит. Это не вступает в силу, почему?
здесь пример проекта, который показывает, что он работает. вы можете видеть, что он работает, просматривая предварительный просмотр визуального редактора, который выглядит не так, как показано во время выполнения. Я думаю, что ваша ошибка заключалась в том, что вы не установили 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>
TestActivity.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);
}
}
findViewById
не будет работать для него, кроме как для нахождения первого, который есть в xml.