当我按下添加按钮时,会显示一个视图,该视图应位于添加按钮的正下方。但是,当我单击按钮时,添加按钮和添加的视图之间会有一些空格。我已经尝试在xml和java文件中将引力设置为top。当我再次按下添加按钮并获得下一个视图时,它将第一个视图推到它应该的位置。我做错了什么?
public class MainActivity extends Activity {
public int count = 1;
int layoutUse[] = {0,0,0,0,0};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 2)
{
//inputName(v);
inputName(v);
}
else
{
}
}
});
Button removeTroop1 = (Button)findViewById(R.id.remove1);
removeTroop1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
removeTroop1();
}
});
Button removeTroop2 = (Button)findViewById(R.id.remove2);
removeTroop2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
removeTroop2();
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
if(layoutUse[0] == 0 && count == 1)
{
LinearLayout mainView = (LinearLayout)findViewById(R.id.manageTroopsMain);
LinearLayout layout1 = (LinearLayout)findViewById(R.id.trpLayout1);
Button troop1 = (Button)findViewById(R.id.troop1);
troop1.setText("Button 1");
mainView.removeView(layout1);
mainView.addView(layout1);
layout1.setVisibility(View.VISIBLE);
layoutUse[0]++;
count++;
}
else if(layoutUse[1] == 0 && count == 2)
{
LinearLayout mainView = (LinearLayout)findViewById(R.id.manageTroopsMain);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.trpLayout2);
Button troop2 = (Button)findViewById(R.id.troop2);
troop2.setText("Button 2");
mainView.removeView(layout2);
mainView.addView(layout2);
layout2.setVisibility(View.VISIBLE);
layoutUse[1]++;
count++;
}
}
public void removeTroop1(){
LinearLayout layout = (LinearLayout)findViewById(R.id.trpLayout1);
layout.setVisibility(View.GONE);
layoutUse[0]--;
count--;
}
public void removeTroop2(){
LinearLayout layout = (LinearLayout)findViewById(R.id.trpLayout2);
layout.setVisibility(View.GONE);
layoutUse[1]--;
count--;
}
}
答案 0 :(得分:1)
我明白了。在我的xml文件中,我将视图的初始可见性设置为不可见。设置它们来解决这个问题。我猜这些观点正在被隐藏起来,所以通过设置它们已经消失它们真的不见了。