下面列出了怎么用android.widget.GridLayout的API类实例代码及写法,或者点击链接到github查看源代码。
public void reinitializeViews(GridLayout gridLayout) {
if(getActivity() != null) {
removeFromGrid(gridLayout);
nameView = new TextView(getActivity());
visibleView = new TextView(getActivity());
usedView = new TextView(getActivity());
initializeTextView(nameView, gridLayout, POSE_NAME_COLUMN);
initializeTextView(visibleView, gridLayout, POSE_VISIBLE_COLUMN);
initializeTextView(usedView, gridLayout, POSE_USED_COLUMN);
initializeViewsAsEmpty();
}
}
/**
* Factory method to initialize each text view and add it to the layout
* @param view text view to be initialized
* @param layout layout to which the view is to be added
* @param columnId column of the layout to which the view is to be added
*/
private void initializeTextView(
TextView view,
GridLayout layout,
int columnId){
layout.addView(view);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = GridLayout.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.WRAP_CONTENT;
param.rightMargin = 5;
param.topMargin = 5;
view.setTextSize(11);
view.setWidth(TEXT_FIELD_WIDTH[columnId]);
view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(columnId);
param.rowSpec = GridLayout.spec(rowId);
view.setLayoutParams (param);
}
@Override
public void reinitializeViews(GridLayout gridLayout){
if(getActivity() != null) {
removeFromGrid(gridLayout);
nameView = new TextView(getActivity());
latView = new TextView(getActivity());
lonView = new TextView(getActivity());
altView = new TextView(getActivity());
clockBiasView = new TextView(getActivity());
initializeTextView(nameView, gridLayout, POSE_NAME_COLUMN);
initializeTextView(latView, gridLayout, POSE_LAT_COLUMN);
initializeTextView(lonView, gridLayout, POSE_LON_COLUMN);
initializeTextView(altView, gridLayout, POSE_ALT_COLUMN);
initializeTextView(clockBiasView, gridLayout, POSE_CLOCK_BIAS_COLUMN);
}
}
private void initializeTextView(
TextView view,
GridLayout layout,
int columnId){
layout.addView(view);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = GridLayout.LayoutParams.WRAP_CONTENT;
param.width = GridLayout.LayoutParams.WRAP_CONTENT;
param.rightMargin = 5;
param.topMargin = 5;
view.setTextSize(11);
view.setWidth(TEXT_FIELD_WIDTH[columnId]);
view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(columnId);
param.rowSpec = GridLayout.spec(rowId);
view.setLayoutParams (param);
}
public void load(){
saved = this.getSharedPreferences("com.ahmedmaghawry.ahmedezzat2048", Context.MODE_PRIVATE);
highName = saved.getString("Name", "");
highScore = saved.getInt("Score", 0);
TextView highna = (TextView) findViewById(R.id.bestName);
TextView highnu = (TextView) findViewById(R.id.bestScore);
highna.setText(highName + "");
highnu.setText(highScore + "");
for (int i = 0; i < 16; i++) {
board.add("");
}
int first_index = rand.nextInt(16);
board.set(first_index, "2");
GridLayout grid = (GridLayout) findViewById(R.id.grid);
TextView te = (TextView) grid.getChildAt(first_index);
te.setText("2");
drawit();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_saveload_state, container, false);
GridLayout grid = rootView.findViewById(R.id.grid_state_slots);
for (int childIndex = 0; childIndex < grid.getChildCount(); childIndex++)
{
Button button = (Button) grid.getChildAt(childIndex);
button.setOnClickListener(this);
}
// So that item clicked to start this Fragment is no longer the focused item.
grid.requestFocus();
return rootView;
}
private void initView(View view, Bundle savedInstanceState) {
layout = new BrowserWeiboMsgLayout();
layout.username = (TextView) view.findViewById(R.id.username);
layout.content = (TextView) view.findViewById(R.id.content);
layout.recontent = (TextView) view.findViewById(R.id.repost_content);
layout.time = (TextView) view.findViewById(R.id.time);
layout.location = (TextView) view.findViewById(R.id.location);
layout.source = (TextView) view.findViewById(R.id.source);
layout.mapView = (ImageView) view.findViewById(R.id.map);
layout.comment_count = (TextView) view.findViewById(R.id.comment_count);
layout.repost_count = (TextView) view.findViewById(R.id.repost_count);
layout.count_layout = view.findViewById(R.id.count_layout);
layout.avatar = (ProfileTopAvatarImageView) view.findViewById(R.id.avatar);
layout.content_pic = (WeiboDetailImageView) view.findViewById(R.id.content_pic);
layout.content_pic_multi = (GridLayout) view.findViewById(R.id.content_pic_multi);
layout.repost_pic = (WeiboDetailImageView) view.findViewById(R.id.repost_content_pic);
layout.repost_pic_multi = (GridLayout) view.findViewById(R.id.repost_content_pic_multi);
layout.repost_layout = (LinearLayout) view.findViewById(R.id.repost_layout);
}
public void repopulate() {
final List<ComponentName> quickRowOrder = db().getAppCategoryOrder(QUICK_ROW_CAT);
mQuickRow.postDelayed(new Runnable() {
@Override
public void run() {
mQuickRow.removeAllViews();
for (ComponentName actvname : quickRowOrder) {
AppLauncher app = db().getApp(actvname);
if (!appAlreadyHere(app)) {
ViewGroup item = mMainActivity.getLauncherView(app, true);
if (item != null) {
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.TOP);
mQuickRow.addView(item, lp);
}
}
}
}
}, 400);
}
private View createIcon(GridLayout parent, int rowIndex) {
// The icon has a pre-defined width.
ImageView icon = new ImageView(parent.getContext());
icon.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
icon.setBackgroundResource(R.drawable.payments_ui_logo_bg);
icon.setImageResource(mOption.getDrawableIconId());
icon.setMaxWidth(mIconMaxWidth);
// The icon floats to the right of everything.
GridLayout.LayoutParams iconParams = new GridLayout.LayoutParams(
GridLayout.spec(rowIndex, 1, GridLayout.CENTER), GridLayout.spec(2, 1));
iconParams.topMargin = mVerticalMargin;
ApiCompatibilityUtils.setMarginStart(iconParams, mLargeSpacing);
parent.addView(icon, iconParams);
icon.setOnClickListener(OptionSection.this);
return icon;
}
@Override
protected void onResume() {
super.onResume();
GridLayout sortArea = findViewById(R.id.sort_area);
if (isLandscape()) {
numcolumns = 6;
} else {
numcolumns = 3;
}
sortArea.setColumnCount(numcolumns);
//override super class
LinearLayout centercol = findViewById(R.id.centercol);
centercol.setOrientation(LinearLayout.VERTICAL);
findViewById(R.id.score_total_correct_area).setVisibility(View.GONE);
findViewById(R.id.score_level_percent_area).setVisibility(View.GONE);
}
@Override
protected void createMainSectionContent(LinearLayout mainSectionLayout) {
Context context = mainSectionLayout.getContext();
// Add a label that will be used to indicate that the total cart price has been updated.
addUpdateText(mainSectionLayout);
// The breakdown is represented by an end-aligned GridLayout that takes up only as much
// space as it needs. The GridLayout ensures a consistent margin between the columns.
mBreakdownLayout = new GridLayout(context);
mBreakdownLayout.setColumnCount(2);
LayoutParams breakdownParams =
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
breakdownParams.gravity = Gravity.END;
mainSectionLayout.addView(mBreakdownLayout, breakdownParams);
}
private View createOptionIcon(GridLayout parent, int rowIndex, boolean editIconExists) {
// The icon has a pre-defined width.
ImageView optionIcon = new ImageView(parent.getContext());
optionIcon.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
optionIcon.setBackgroundResource(R.drawable.payments_ui_logo_bg);
optionIcon.setImageDrawable(mOption.getDrawableIcon());
optionIcon.setMaxWidth(mIconMaxWidth);
// Place option icon at column three if no edit icon.
int columnStart = editIconExists ? 2 : 3;
GridLayout.LayoutParams iconParams = new GridLayout.LayoutParams(
GridLayout.spec(rowIndex, 1, GridLayout.CENTER),
GridLayout.spec(columnStart, 1));
iconParams.topMargin = mVerticalMargin;
parent.addView(optionIcon, iconParams);
optionIcon.setOnClickListener(OptionSection.this);
return optionIcon;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
mRootView = (ViewGroup) layoutInflater.inflate(R.layout.dialog_colors, null);
mAlphaSeekBar = (SeekBar) mRootView.findViewById(android.R.id.progress);
mAlphaSeekBar.setOnSeekBarChangeListener(alphaSeekListener);
mAlphaSeekBar.setMax(255);
mAlphaSeekBar.setProgress(getValueAlpha(false));
mColorGrid = (GridLayout) mRootView.findViewById(R.id.color_grid);
mColorGrid.setColumnCount(mPreference.mNumColumns);
repopulateItems();
return new AlertDialog.Builder(getActivity())
.setView(mRootView)
.setNegativeButton(android.R.string.cancel, clickListener)
.setPositiveButton(android.R.string.ok, clickListener)
.create();
}
private void setUpClsTitle(){
for (int i=0; i<TITLE_DATA.length; ++i){
String content = TITLE_DATA[i];
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
//第一列的时候
if (i == 0){
params.width = mTableDistance;
}
else {
//添加分割线
View divider = getLayoutInflater().inflate(R.layout.grid_title_form,mGlClsTitle,false);
mGlClsTitle.addView(divider);
params.width = mTableDistance * 2;
}
params.height = GridLayout.LayoutParams.MATCH_PARENT;
TextView textView = new TextView(this);
textView.setTextColor(getResources().getColor(R.color.blue));
textView.setText(content);
textView.setGravity(Gravity.CENTER);
mGlClsTitle.addView(textView,params);
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (! cursor.moveToFirst()) {
return;
}
ArrayList<VideoType.Cast> castArrayList;
int id = getArguments().getInt(BUNDLE_LOADER_TYPE);
if (id == TYPE.MOVIE.ordinal()) {
castArrayList = createMovieCastList(cursor);
} else {
castArrayList = createTVShowCastList(cursor);
}
UIUtils.setupCastInfo(getActivity(), castArrayList,
(GridLayout) getView().findViewById(R.id.cast_list),
AllCastActivity.buildLaunchIntent(getActivity(),
getArguments().getString(BUNDLE_TITLE),
castArrayList));
}
/**
* Constructor that allows a custom computer move generator to be supplied.
*
* @param context Current application context
* @param gameBoard GridLayout containing the buttons that make up the tic-tac-toe board
* @param resetButton Button to reset the board to a new game
* @param computerMoveGenerator Custom computer move generator for this game
*/
public SetupWizardTicTacToeController(
Context context,
GridLayout gameBoard,
Button resetButton,
TicTacToeComputerMoveGenerator computerMoveGenerator) {
this.context = context;
this.gameBoard = gameBoard;
emptySpacesIndices = new ArrayList<>();
this.computerMoveGenerator = computerMoveGenerator;
this.resetButton = resetButton;
this.resetButton.setOnClickListener(view -> resetGameBoard());
resetGameBoard();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
mRootView = (ViewGroup) layoutInflater.inflate(R.layout.dialog_colors, null);
mAlphaSeekBar = (SeekBar) mRootView.findViewById(android.R.id.progress);
mAlphaSeekBar.setOnSeekBarChangeListener(alphaSeekListener);
mAlphaSeekBar.setMax(255);
mAlphaSeekBar.setProgress(getValueAlpha(false));
mColorGrid = (GridLayout) mRootView.findViewById(R.id.color_grid);
mColorGrid.setColumnCount(mPreference.mNumColumns);
repopulateItems();
return new AlertDialog.Builder(getActivity())
.setView(mRootView)
.setNegativeButton(android.R.string.cancel, clickListener)
.setPositiveButton(android.R.string.ok, clickListener)
.create();
}
private void initView(View view, Bundle savedInstanceState) {
layout = new BrowserWeiboMsgLayout();
layout.username = (TextView) view.findViewById(R.id.username);
layout.content = (TextView) view.findViewById(R.id.content);
layout.recontent = (TextView) view.findViewById(R.id.repost_content);
layout.time = (TextView) view.findViewById(R.id.time);
layout.location = (TextView) view.findViewById(R.id.location);
layout.source = (TextView) view.findViewById(R.id.source);
layout.mapView = (ImageView) view.findViewById(R.id.map);
layout.comment_count = (TextView) view.findViewById(R.id.comment_count);
layout.repost_count = (TextView) view.findViewById(R.id.repost_count);
layout.count_layout = view.findViewById(R.id.count_layout);
layout.avatar = (ProfileTopAvatarImageView) view.findViewById(R.id.avatar);
layout.content_pic = (WeiboDetailImageView) view.findViewById(R.id.content_pic);
layout.content_pic_multi = (GridLayout) view.findViewById(R.id.content_pic_multi);
layout.repost_pic = (WeiboDetailImageView) view.findViewById(R.id.repost_content_pic);
layout.repost_pic_multi = (GridLayout) view.findViewById(R.id.repost_content_pic_multi);
layout.repost_layout = (LinearLayout) view.findViewById(R.id.repost_layout);
}
@Override
public void removeFromGrid(GridLayout grid) {
grid.removeView(nameView);
grid.removeView(latView);
grid.removeView(lonView);
grid.removeView(altView);
grid.removeView(clockBiasView);
}
private void redrawGrid(GridLayout grid, HashMap<CalculationModule, CalculationGridItem> items){
grid.setRowCount(items.size() + 1);
for(Map.Entry<CalculationModule, CalculationGridItem> entry: items.entrySet()) {
entry.getValue().reinitializeViews(grid);
}
}
private void Generate() {
if (khalas) {
int theChoices[] = {2, 2, 2, 4, 2, 2, 2, 4, 2, 2, 4};
int Chosen = theChoices[rand.nextInt(theChoices.length)];
int placeIt = rand.nextInt(16);
if (board.get(placeIt) == "") {
board.set(placeIt, Chosen + "");
GridLayout grid = (GridLayout) findViewById(R.id.grid);
TextView te = (TextView) grid.getChildAt(placeIt);
te.setText(Chosen + "");
} else {
Generate();
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private void endIt() {
GridLayout grid = (GridLayout) findViewById(R.id.grid);
TextView now = (TextView) findViewById(R.id.nowScore);
TextView highS = (TextView) findViewById(R.id.bestScore);
TextView highN = (TextView) findViewById(R.id.bestName);
TextView End = (TextView) findViewById(R.id.Ended);
TextView high1 = (TextView) findViewById(R.id.newHighS);
TextView high2 = (TextView) findViewById(R.id.newHighS2);
EditText edit = (EditText) findViewById(R.id.EditS);
Button btn = (Button) findViewById(R.id.button);
int Now = Integer.parseInt(now.getText() + "");
int HighS = Integer.parseInt(highS.getText() + "");
End.setVisibility(View.VISIBLE);
End.setAlpha(0f);
End.animate().alpha(0.5f).setDuration(1000);
khalas = false;
if (Now >= HighS) {
grid.setClickable(false);
grid.setEnabled(false);
high1.setVisibility(View.VISIBLE);
high1.setAlpha(0f);
high1.animate().alpha(0.5f).setDuration(1000);
high2.setVisibility(View.VISIBLE);
high2.setAlpha(0f);
high2.animate().alpha(0.5f).setDuration(1000);
edit.setVisibility(View.VISIBLE);
edit.setAlpha(0f);
edit.animate().alpha(0.5f).setDuration(1000);
btn.setVisibility(View.VISIBLE);
btn.setAlpha(0f);
btn.animate().alpha(0.5f).setDuration(1000);
}
}
private void setChildrenOnClickListener(AppCompatRadioButton child) {
GridLayout parent = (GridLayout) child.getParent();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = parent.getChildAt(i);
if (v instanceof AppCompatRadioButton) {
if (((RadioButton) v).isChecked()) {
activeRadioButton = (AppCompatRadioButton) v;
}
v.setOnClickListener(this);
}
}
}
private void setIconSheetLayout(GridLayout iconSheet) {
FrameLayout.LayoutParams lp;
if (mAppPreferences.getBoolean(getString(R.string.pref_key_center_sheet), true)) {
lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
} else {
lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
iconSheet.setLayoutParams(lp);
}
private void createIconSheet(String category, int pos) {
final GridLayout iconSheet = new GridLayout(MainActivity.this);
if (mIconSheet == null) mIconSheet = iconSheet;
mIconSheets.put(category, iconSheet);
mRevCategoryMap.put(iconSheet, category);
iconSheet.setColumnCount(mColumns);
iconSheet.setOnDragListener(mMainDragListener);
setIconSheetLayout(iconSheet);
final TextView categoryTab = createCategoryTab(category, iconSheet, pos);
mCategoryTabs.put(category, categoryTab);
mRevCategoryMap.put(categoryTab, category);
}
private void removeIconSheetRecv(Message msg) {
Bundle data = msg.getData();
String category = data.getString("category");
GridLayout iconSheet = mIconSheets.get(category);
if (iconSheet!=null) {
try {
iconSheet.removeAllViews();
} catch (Throwable t) {
Log.e(TAG, t.getMessage(), t);
Toast.makeText(this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}
private void showNoIconsRecv(Message msg) {
Bundle data = msg.getData();
String category = data.getString("category");
GridLayout iconSheet = mIconSheets.get(category);
if (iconSheet!=null) {
TextView v = new TextView(this);
v.setText(R.string.nothing_in_cat);
v.setTextColor(mStyle.getTextColor());
v.setTextSize(mStyle.getLauncherFontSize());
v.setPadding(2,40,2,2);
v.setMaxLines(3);
iconSheet.addView(v);
}
}
private void addAppToIconSheet(GridLayout iconSheet, AppLauncher app, int pos, boolean reuse) {
if (app != null) {
try {
if (((app.isWidget() || app.isLink()) && isAppInstalled(app.getPackageName())) || mLaunchApp.isValidActivity(app)) {
ViewGroup item = getLauncherView(app, false, reuse);
if (item != null) {
if (!app.iconLoaded()) {
app.loadAppIconAsync(this);
}
item.setTranslationX(0);
ViewGroup parent = (ViewGroup) item.getParent();
if (parent != null) parent.removeView(item);
GridLayout.LayoutParams lp = getAppLauncherLayoutParams(iconSheet, app);
iconSheet.addView(item, pos, lp);
}
} else {
db().deleteApp(app.getComponentName());
Log.d(TAG, "removed " + app.getPackageName() + " " + app.getActivityName() + ": activity not valid.");
}
} catch (Exception e) {
Log.e(TAG, "exception adding icon to sheet", e);
Toast.makeText(this,"Couldn't place icon: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Log.d(TAG, "Not showing recent: Null.");
}
}
private void makeColorPresetButton(int color) {
FrameLayout outframe = new FrameLayout(getContext());
outframe.setBackgroundColor(Color.BLACK);
outframe.setPadding(6,6,6,6);
FrameLayout frame = new FrameLayout(getContext());
//frame.setPadding(6,6,6,6);
//frame.setBackgroundColor(Color.BLACK);
frame.setBackgroundResource(R.drawable.bwg);
TextView c = new TextView(getContext());
c.setText(" ");
c.setTextSize(22);
c.setBackgroundColor(color);
// if (color==Color.TRANSPARENT) {
// c.setBackgroundResource(R.drawable.transparentgrid);
// }
c.setTag(color);
c.setClickable(true);
c.setOnClickListener(setColorListener);
frame.addView(c);
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.setMargins(24, 16, 24, 16);
outframe.setPadding(6,6,6,6);
outframe.addView(frame);
colorPresets.addView(outframe, lp);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View rootView = layoutInflater.inflate(R.layout.dialog_colors, null);
mColorGrid = (GridLayout) rootView.findViewById(R.id.color_grid);
mColorGrid.setColumnCount(mPreference.mNumColumns);
repopulateItems();
return new AlertDialog.Builder(getActivity())
.setView(rootView)
.create();
}