要让一个TextView始终位于另一个TextView下方,可以使用布局文件中的LinearLayout和android:layout_below属性。下面是一个示例代码:
布局文件(activity_main.xml):
Java代码(MainActivity.java):
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = findViewById(R.id.layout);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.custom_layout, layout, false);
TextView textView1 = view.findViewById(R.id.textView1);
TextView textView2 = view.findViewById(R.id.textView2);
textView1.setText("Custom TextView 1");
textView2.setText("Custom TextView 2");
layout.addView(view);
}
}
在这个示例中,我们使用了LinearLayout作为根布局,并设置了垂直方向的orientation。然后,我们在代码中使用LayoutInflater将一个自定义布局(custom_layout.xml)充气到LinearLayout中。
在自定义布局中,我们使用了android:layout_below="@id/textView1"属性来确保TextView 2始终位于TextView 1下方。
请注意,我们要在LinearLayout中添加自定义布局视图,以便它们显示在屏幕上。