public class MainActivity extends Activity implements OnGestureListener
{
private LinearLayout mainlayout;
private TextView tv;
private GestureDetector gestureScanner;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gestureScanner = new GestureDetector(MainActivity.this,this);
mainlayout = new LinearLayout(this);
mainlayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
mainlayout.setBackgroundColor(Color.GREEN);
tv = new TextView(getApplicationContext());
tv.setBackgroundColor(Color.YELLOW);
tv.setTextColor(Color.BLUE);
tv.setGravity(Gravity.CENTER); //here, why tv located top-left
tv.setTextSize(20);
tv.setLayoutParams(new LinearLayout.LayoutParams(320,80));
mainlayout.addView(tv);
setContentView(mainlayout);
}
}
代码如上,我实现了xml以外的Java代码布局,添加了TextView,tv。使用tv.setGravity(Gravity.CENTER)来定位它,为什么我无法改变电视位置。我在等你的回答。先感谢您。我很感激你的善意。
答案 0 :(得分:2)
您使用该代码设置TextView内容的重力,而不是TextView本身。尝试使用:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lp.gravity = Gravity.CENTER;
tv.setLayoutParams(lp);
修改强>
事实证明,使用LinearLayout是可行的,但只有在更改方向并且在整个布局中只需要一个TextView时才有效:
private LinearLayout mainlayout;
private TextView tv;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
mainlayout = new LinearLayout(this);
mainlayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mainlayout.setBackgroundColor(Color.GREEN);
mainlayout.setOrientation(LinearLayout.VERTICAL);
tv = new TextView(getApplicationContext());
tv.setBackgroundColor(Color.YELLOW);
tv.setTextColor(Color.BLUE);
tv.setTextSize(20);
tv.setLayoutParams(new LinearLayout.LayoutParams(320, 80));
mainlayout.addView(tv);
setContentView(mainlayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
tv.setLayoutParams(lp);
tv.setText("LOL");
}
上面的代码导致:
答案 1 :(得分:1)
mainlayout = new RelativeLayout(this);
mainlayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mainlayout.setBackgroundColor(Color.GREEN);
tv = new TextView(getApplicationContext());
tv.setBackgroundColor(Color.YELLOW);
tv.setTextColor(Color.BLUE);
tv.setTextSize(20);
tv.setGravity(Gravity.CENTER);
tv2 = new TextView(getApplicationContext());
tv2.setBackgroundColor(Color.YELLOW);
tv2.setTextColor(Color.BLUE);
tv2.setTextSize(20);
tv2.setGravity(Gravity.CENTER);
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(320, 80);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
tv.setLayoutParams(params);
RelativeLayout.LayoutParams params2= new RelativeLayout.LayoutParams(320, 80);
tv2.setLayoutParams(params2);
mainlayout.addView(tv);
mainlayout.addView(tv2);
setContentView(mainlayout);