标题可能听起来令人困惑我知道,我每次点击按钮时都会添加一个视图,由文本视图和按钮组成。我正在为每个添加的视图设置一个只有view.setID(++i)
的ID,每个添加的按钮(在视图中)只需button.setID(++n)
,n
从1000开始,因为我不会有超过1000个添加的视图。
这是我得到的:
public class MainActivity extends AppCompatActivity {
GridLayout gridLayout;
static int i;
static int n = 1000;
private Button theButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout)findViewById(R.id.gamehistory);
Button b = (Button)findViewById(R.id.Button01);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
theButton = new Button(MainActivity.this);
TextView theText = new TextView(MainActivity.this);
theText.setGravity(Gravity.CENTER_HORIZONTAL);
LinearLayout theLayout = new LinearLayout(MainActivity.this);
theLayout.setOrientation(LinearLayout.VERTICAL);
theLayout.setBackgroundColor(Color.parseColor("#8BAAC3"));
theLayout.setId(++i);
theButton.setId(++n);
theButton.setText(theButton.getId() + "");
theText.setText(theLayout.getId() + "");
theLayout.addView(theButton);
theLayout.addView(theText);
gridLayout.addView(theLayout);
GridLayout.LayoutParams lp = (GridLayout.LayoutParams) theLayout.getLayoutParams();
lp.setMargins(10, 10, 10, 10);
}
});
我需要的是当我点击创建的按钮时,对应的视图被破坏,并且下一个视图后退一步感觉父母的间隙是GridLayout
答案 0 :(得分:1)
最简单的方法是。
?xxx=yyy
但是,您似乎可以考虑使用RecyclerView。您可以在适配器中添加/删除项目,并为您更新视图。
修改强>
使用A RecyclerView时,您必须指定两个基本组件。
RecyclerAdapter - 将数据转换为视图(行,卡,单元格等)
LayoutManger - 最常见的是LinearLayoutManger和GridLayoutManager,它们定义了适配器中的视图如何相互呈现,并处理滚动。
如果需要,还可以添加一些选项。
ItemDecoration - 定义单元格的背景或叠加层。 (E.G.为列表中的每个其他视图绘制灰色背景)
ItemTouchHelper - 执行大部分重击(例如滑动以删除)并拖动(例如拖动以重新排列)操作。
我强烈建议您熟悉RecyclerView,当您需要在屏幕上显示项目列表时,它应该是您的goto组件。
答案 1 :(得分:1)
在将视图添加到GridLayout
-
theLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gridLayout.removeView(theLayout);
}
});
theButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gridLayout.removeView(theLayout);
}
});
为此,您需要进行theLayout
最终
final LinearLayout theLayout = new LinearLayout(LauncherActivity.this);