尝试创建一个简单的ABC和123s应用程序。我的初始布局有两个按钮,1个用于字母,1个用于数字。如果单击字母按钮,我想转到下一个片段,该片段将保存所有字母表(A-Z)的26个按钮。对于数字,10个按钮(0-9)。我的问题是,如何有效地使用26个按钮/ 10个按钮填充布局文件,而无需在XML文件中写入每个按钮?
答案 0 :(得分:1)
您可以以编程方式向视图添加按钮。在片段的onCreateView函数中尝试这个。
//mView is your fragment root, and container is defined in XML
LinearLayout container = (LinearLayout)mView.findViewById(R.id.alpha_container)
String[] letters = {A, B, C, ..., Z};
for(int i=0; i<letters.length; i++) {
Button letter_btn = new Button(getActivity());
letter.setText(letters[i]);
container.addView(letter_btn, i);
}
这将以编程方式为字母数组中的每个元素创建一个按钮。您可以相应地附加onClickListener并按文本内容跟踪按钮或为其指定标记/ ID。
答案 1 :(得分:0)
使用gridview
活动xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
您的活动
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new GridAdapter (this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
gridView适配器
public class GridAdapter extends BaseAdapter {
private Context mContext;
// Constructor
public GridAdapter (Context c) {
mContext = c;
}
public int getCount() {
return alphabets.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new TextView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
TextView txView;
if (convertView == null) {
txView= new TextView (mContext);
txView.setLayoutParams(new GridView.LayoutParams(85, 85));
txView.setPadding(8, 8, 8, 8);
}
else
{
txView= (TextView) convertView;
}
txView.setText(alphabets[position]);
**Update**
txView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//your code here
switch(position){
case 0:
Toast.makeText(this,"A",Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(this,"B",Toast.LENGTH_LONG).show();
break;
........SoOn
}
}});
return txView;
}
// array
public String[] alphabets= {
"A","B","C","D"
};
}